在使用HashSet 的时候往往需要重写他的equals和hashCode方法,简单记录一下调用过程做个备忘
1.当hashcode不相等时,两个对象则不相等,不调用equals
2.当hashcode相等时,则看两个对象是否equals,即调用equals方法比较
1.当hashcode不相等时,两个对象则不相等,不调用equals
2.当hashcode相等时,则看两个对象是否equals,即调用equals方法比较
public class Person {
private String name;
private int age ;
public Person(){}
public Person(String name,int age){
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
int flag = (int)(Math.random()*100);
System.out.println("hashCode : " + flag + "(" + this.name + " : " + this.age +")");
return flag;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Person){
Person p = (Person)obj;
if(this.name.equals(p.name) && this.age == p.age) {
System.out.println("equals : true");
return true;
}else{
System.out.println("equals : false");
return false;
}
}
System.out.println("equals : false");
return false;
}
}
@Test
public void test(){
Person p1 = new Person("tom",22);
Person p2 = new Person("tom",22);
Person p3 = new Person("jack",22);
boolean result = p1.equals(p2);
System.out.println(result);
System.out.println("========================");
HashSet<Person> set = new HashSet<Person>();
set.add(p1);
System.out.println("========================");
set.add(p2);
System.out.println("========================");
set.add(p3);
System.out.println("set size : " + set.size());
System.out.println("========================");
Iterator<Person> its = set.iterator();
while(its.hasNext()){
Person p = its.next();
System.out.println(p.getName() + " : " + p.getAge());
}
}
/*
equals : true
true
========================
hashCode : 23(tom : 22)
========================
hashCode : 9(tom : 22)
========================
hashCode : 89(jack : 22)
set size : 3
========================
tom : 22
tom : 22
jack : 22
*/