最近我一直在使用Java的HashMap,并且遇到了一些有趣的行为。我目前使用它来存储具有多个字段的键/值对象。要做到这一点,我已经重写hashCode()和equals()方法如下:重写hashCode()和equals()的Java HashMap不会返回任何数据
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()方法,该方法执行get(),检查是否为NULL。进入get()会显示循环,只有在返回NULL之前运行一次。所以,这是一个HashMap问题(可能不是)或(更可能),我可能做错了什么?预先感谢您的帮助。
总是应该使用`@ Overrides`的完美理由。 – 2010-11-24 17:48:14
@matt b:我正要补充一点:) – 2010-11-24 17:48:48