Person类中重写了hashCode 跟equals方法,在HashSet集合中添加两次同一对象时在比较得知哈希值相等的时候为什么没有调用equals方法比较就认为元素已经存在了呢?
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
get、set方法省略...
@Override
public int hashCode() {
int hashCode = this.name.hashCode() + this.age * 27;
System.out.println(this + "....hashCode" + hashCode);
return hashCode;
}
@Override
public boolean equals(Object obj) {
Person p = (Person) obj;
System.out.println(this + "...equals..." + p);
return this.name.equals(p.name) && this.age == p.age;
}
@Override
public String toString() {
return this.name + "," + this.age;
}
测试类代码:
public class HashSetTest {
public static void main(String[] args) {
HashSet hs = new HashSet();
Person ps = new Person("test", 21);
hs.add(ps);
hs.add(ps);
for (Iterator it = hs.iterator(); it.hasNext(); ) {
Person p = (Person) it.next();
System.out.println(p.getName() + "," + p.getAge());
}
}
}
结果:
test,21....hashCode3557065
test,21....hashCode3557065
test,21
Smart猫小萌
繁星coding
子衿沉夜
交互式爱情
相关分类