【发布时间】:2014-08-15 18:20:02
【问题描述】:
当我运行此代码时,为什么只调用hashCode() 而不是equals 方法,而我的hashCode() 实现为HashSet 的两个条目生成相同的hashCode?
import java.util.HashSet;
public class Test1 {
public static void main(String[] args) {
Student st=new Student(89);
HashSet st1=new HashSet();
st1.add(st);
st1.add(st);
System.out.println("Ho size="+st1.size());
}
}
class Student{
private int name;
private int ID;
public Student(int iD) {
super();
this.ID = iD;
}
@Override
public int hashCode() {
System.out.println("Hello-hashcode");
return ID;
}
@Override
public boolean equals(Object obj) {
System.out.println("Hello-equals");
if(obj instanceof Student){
if(this.ID==((Student)obj).ID){
return true;
}
else{
return false;
}
}
return false;
}
}
这个的输出是:
Hello-hashcode
Hello-hashcode
Ho size=1
【问题讨论】:
-
您是否有意不重写 hashCode() 方法?
-
@Vishrant - 这不是重复的 - “为什么不能调用
equals”部分未包含在链接的问题中。 -
san9w,我已经编辑了标题 - 看看你是否还好/恢复/改进。
标签: java