<分区>
这是我的代码:
public class testGui {
public static void main(String[] arg){
class TESTS{
String t;
public TESTS(String t){
this.t = t;
}
@Override
public boolean equals(Object x){
System.out.println("My method is called...");
if(x instanceof TESTS){
TESTS zzz = (TESTS) x;
return zzz.t.compareTo(t)==0;
}
else return false;
}
}
HashSet<TESTS> allItems = new HashSet<TESTS>();
allItems.add(new TESTS("a"));
allItems.add(new TESTS("a"));
System.out.println(allItems.contains(new TESTS("a")));
}
}
我不明白为什么 hashset contains 方法没有像他们的规范中提到的那样调用我的 equals 方法:
More formally, adds the specified element, o, to this set if this set contains no element e such that (o==null ? e==null : o.equals(e))
我的代码返回 false 并且没有进入我的 equals 方法。
非常感谢您的回答!