这是java main()方法:
public static void main(String[] args) {
HashSet set = new HashSet();
Mapper test = new Mapper("asd", 0);
set.add(test);
System.out.println(new Mapper("asd", 0).equals(test));
System.out.println(set.contains(new Mapper("asd", 0)));
}
我的映射器类是:
class Mapper {
String word;
Integer counter;
Mapper (String word, Integer counter) {
this.word = word;
this.counter = counter;
}
public boolean equals(Object o) {
if ((o instanceof Mapper) && (((Mapper)o).word == this.word)) {
return true;
}
return false;
}
}
结果是:
true
false
从 HashSet 规范中,在这个方法中我读到了这样的内容:“如果此集合包含指定的元素,则返回 true。更正式地说,当且仅当此集合包含元素 e 且满足 (o==null ? e= =null : o.equals(e))."
那么,谁能解释一下我哪里错了?或者...?
谢谢。
最佳答案
您需要实现适当的 hashCode()
函数。
public int hashCode() {
// equal items should return the same hashcode
}
Java 实用程序 java.util
包含许多依赖哈希的类。允许人们按照自己认为合适的方式重写 equals()
意味着人们还必须正确重写 hashCode()
才能匹配。
hashCode()
的正确实现将为任何两个 equals()
返回 true 的对象返回相同的哈希值。与哈希相关的函数在检查对象是否相等之前先检查哈希是否相等(以解决哈希冲突)。
关于java - java.util.HashSet 中的 contains() 方法的行为不符合我的预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5726460/