1
我有一个HashMap,它将自定义对象TokenDocumentPair
映射到Double
。该TokenDocumentPair
如下:尽管hashCode/equals被覆盖,HashMap返回null
static class TokenDocumentPair {
int documentNum;
String token;
public TokenDocumentPair(String token, int documentNum) {
this.token = token;
this.documentNum = documentNum;
}
public boolean equals(TokenDocumentPair other) {
return (this.documentNum == other.documentNum && this.token.equals(other.token));
}
public int hashCode() {
int result = 1;
result = 37 * result + Objects.hashCode(this.documentNum);
result = 37 * result + Objects.hashCode(this.token);
return result;
}
public String toString() {
return String.format("[Document #%s, Token: %s]", documentNum, token);
}
}
的问题是,当我创建TokenDocumentPair pair1 = new TokenDocumentPair("hello", 1)
,将其存储到一个HashMap<TokenDocumentPair, Double> map
,并尝试与TokenDocumentPair pair2 = new TokenDocumentPair("hello", 1)
取水的时候,它返回null
。然而,我的印象是,由于我的hashcode和equals方法匹配并基于存储的两个字段,哈希映射将能够找到原始的pair1
并将其值返回给我。
TokenDocumentPair pair1 = new TokenDocumentPair("hello", 1);
TokenDocumentPair pair2 = new TokenDocumentPair("hello", 1);
assert pair1.hashCode() == pair2.hashCode(); // ok
assert pair1.equals(pair2); // ok
HashMap<TokenDocumentPair, Double> map = new HashMap<>();
map.put(pair1, 0.0);
map.get(pair2); // null
map.containsKey(pair2); // false
我在做什么错在这里?
啊,谢谢!这样一个愚蠢的错误... – kk415kk