【发布时间】:2010-11-24 17:44:36
【问题描述】:
我最近一直在使用 Java 的 HashMap,并且遇到了一些有趣的行为。我目前正在使用它来存储具有多个字段的键/值对象。为此,我重写了 hashCode() 和 equals(),如下所示:
public final class TransitionState {
private String mStackSymbol;
private String mTransitionSymbol;
private int mState;
private static final int HASH_SEED = 7; //Should be prime
private static final int HASH_OFFSET = 31;
//Constructor and getter methods here
public boolean equals(TransitionState other) {
//Check that we aren't comparing against ourself
if (this == other) {
return true;
}
//Check that we are not comparing against null
if (other == null) {
return false;
}
//Check fields match
if ((mState == other.getState()) &&
(mTransitionSymbol.equals(other.getTransitionSymbol())) &&
(mStackSymbol.equals(other.getStackSymbol()))) {
return true;
} else {
return false;
}
}
public int hashCode() {
int intHash = HASH_SEED;
//Sum hash codes for individual fields for final hash code
intHash = (intHash * HASH_OFFSET) + mState;
intHash = (intHash * HASH_OFFSET) + (mTransitionSymbol == null ? 0 : mTransitionSymbol.hashCode());
intHash = (intHash * HASH_OFFSET) + (mStackSymbol == null ? 0 : mStackSymbol.hashCode());
return intHash;
}
}
现在,我可以毫无问题地将项目放入地图中。然而,检索它们是另一回事。每当我尝试从 HashMap 中获取()时,都会返回 NULL。我编写了一些测试代码来迭代 Map 并打印值,这就是事情变得令人困惑的地方,因为我的关键对象的 hashCode() 与我在我的地图中拥有的匹配并且与已知值的相等性返回 true。示例输出如下(参见表格底部的第四个转换):
Transition Table:
State Symbol Stack Move
--------------------------
1, a, b, (1, pop) with key hashcode 212603 and value hashcode 117943
0, b, a, (0, pop) with key hashcode 211672 and value hashcode 117912
1, b, z, (1, push) with key hashcode 212658 and value hashcode 3459456
0, a, b, (0, pop) with key hashcode 211642 and value hashcode 117912
1, a, z, (0, push) with key hashcode 212627 and value hashcode 3459425
0, a, a, (0, push) with key hashcode 211641 and value hashcode 3459425
0, a, z, (0, push) with key hashcode 211666 and value hashcode 3459425
0, b, z, (1, push) with key hashcode 211697 and value hashcode 3459456
1, b, a, (1, pop) with key hashcode 212633 and value hashcode 117943
1, b, b, (1, push) with key hashcode 212634 and value hashcode 3459456
ababba
Transition from (0, a, z) with hashcode 211666
transition.equals(new TransitionState(0, "a", "z")) = true
HashMap containsKey() = false
Transition not found
false
如您所见,该键将哈希码与映射中的条目匹配,但有人告诉我这是不存在的。我尝试调试 HashMap 的 containsKey() 方法,该方法执行一个检查 NULL 的 get()。进入 get() 显示循环在返回 NULL 之前只运行一次。
那么,这是一个 HashMap 问题(可能不是)还是(更有可能)我做错了什么?提前感谢您的帮助。
【问题讨论】: