【发布时间】:2014-02-26 14:39:47
【问题描述】:
这是我测试 HashSet 的示例代码。 我希望结果是 [3K,1K] 但此代码导致 [1K,3K,3K]
你能告诉我为什么代码没有调用equals吗?
import java.util.HashSet;
class SutdaCard{
private int num;
private boolean isKwang;
SutdaCard(){
this(1,true);
}
SutdaCard(int num, boolean isKwang){
this.num = num;
this.isKwang = isKwang;
}
public String toString(){
return num+(isKwang ? "K":"");
}
public boolean equals(Object obj){
String compareValue = obj.toString();
String thisValue = toString();
System.out.println("equals");
return thisValue.equals(compareValue);
}
public int hashcode(){
return toString().hashCode();
}
}
class exercise11_11 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashSet<SutdaCard> set = new HashSet<SutdaCard>();
set.add(new SutdaCard(3,true));
set.add(new SutdaCard(3,true));
set.add(new SutdaCard(1,true));
System.out.println(set);
}
}
【问题讨论】:
-
如果这是您的代码,那么您在
hashCode方法名称中有错字(小写c)。 -
并且由于@PavelHoral 注意到的结果,当 HashSet 调用真正的 hashCode 时,它会为您的三个项目中的每一个获得不同的值,并且根据规范,它们因此不能相等(所以不调用equals)
-
并使用 @Override 注释来确保您正在覆盖 smth
-
如果你重写方法(这里是 hashCode 和 equals)你应该总是用 @Override 注释这些方法。然后编译器检查该方法是否确实被覆盖。在您的情况下,您会收到方法哈希码的编译器错误,因为这不会覆盖 Object 类中的任何方法。
-
谢谢大家!!我解决了。