2015-06-03 71 views
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 

我在做什么错在这里?

回答

5

equals方法没有被覆盖。你超负荷了。

方法Object#equals覆盖的签名必须是这样的:

@Override 
public boolean equals(Object o) { 
    //... 
} 

为了确保你覆盖的方法,声明方法时使用@Override注解。如果将此注释添加到当前的equals方法中,您将收到编译器错误和正确的错误消息。

+0

啊,谢谢!这样一个愚蠢的错误... – kk415kk

相关问题