friend 们,我在HashSets中发现了这样一个问题。
public class _235 {
private String s;
public _235(String s){
this.s=s;
}
public static void main(String[] args){
HashSet<Object> hs=new HashSet<Object>();
_235 ws1=new _235("ABC");
_235 ws2=new _235("ABC");
String s1=new String("ABC");
String s2=new String("ABC");
hs.add(ws1);
hs.add(ws2);
hs.add(s1);
hs.add(s2);
System.out.println(hs.size());
}
}
当我检查 ws1 和 ws1 都已添加到 HashSet 但不是从 s1 和 s2 中添加时,仅添加了一个字符串。由于 w1 和 w2 没有经过 equal() 我相信 HashSet 不会将它们识别为 equal 2 对象。但为什么字符串 s1 和 s2 的情况不一样呢?如何将它们识别为有意义的平等对象。请解释一下。
最佳答案
HashSet
要求您的自定义类重写在内部用于检测重复元素的 equals()
和 hashcode()
方法。
String
类具有此实现,但您的自定义类 _235
没有此实现。
注意:重要的是要重写equals()
和hashcode()
,而不仅仅是其中之一,否则结果可能是与基于哈希的集合一起使用时不可预测。
You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.
from Effective Java, by Joshua Bloch
这是一个link有很好的解释。
关于java - 向 HashSet 输入有意义的相等数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25227386/