即使hashCode/equals被覆盖,HashMap也会返回null

kk4*_*5kk 1 java hashmap

我有一个HashMap将自定义对象映射TokenDocumentPairDouble.该TokenDocumentPair如下:

  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);
    }
  }
Run Code Online (Sandbox Code Playgroud)

问题是,当我创建时TokenDocumentPair pair1 = new TokenDocumentPair("hello", 1),将其存储到a中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
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

Lui*_*oza 5

equals方法未被覆盖.你已经超载了它.

Object#equals覆盖方法的签名必须如下所示:

@Override
public boolean equals(Object o) {
    //...
}
Run Code Online (Sandbox Code Playgroud)

为了确保覆盖方法,请@Override在声明方法时使用注释.如果将此批注添加到当前equals方法,则会出现编译器错误和正确的错误消息.