Monday, February 29, 2016

[Java] hashCode() and equals()

The set use hashCode() and equals() to decide if the value exists already :

so when override equals() , you have to override hashCode() , too.

and should respect :
if equals() return true, hashCode must be the same,
if hashCode() different, equals must return false.

ex :
class People{
    private String name;
    private int age;
     
    public People(String name,int age) {
        this.name = name;
        this.age = age;
    }  
     
    public void setAge(int age){
        this.age = age;
    }
         
    @Override
    public boolean equals(Object obj) {
        return this.name.equals(((People)obj).name) && this.age== ((People)obj).age;
    }
}
 
 
public class Main {
 
    public static void main(String[] args) {
         
        People p1 = new People("Jack", 12);
        System.out.println(p1.hashCode());
             
        HashMap<People, Integer> hashMap = new HashMap<People, Integer>();
        hashMap.put(p1, 1);
         
        System.out.println(hashMap.get(new People("Jack", 12))); //---> null hashCode is not defined, the program will test the hashCode, and find hashCOde is different, so it think they are different object.(hashcode default projection is from address of the object to int)
    }
}
 
 
solution : override hashCode():

    public int hashCode() {
        return name.hashCode()*37+age;
    }
 attention :  to the changes of the members, the hashCode is nolonger the same, problem for get(key) : 
 
ex:
              People p1 = new People("Jack", 12);
        System.out.println(p1.hashCode());
             
        HashMap<People, Integer> hashMap = new HashMap<People, Integer>();
        hashMap.put(p1, 1);
        p1.setAge(12);
       
        System.out.println(hashMap.get(p1); ->>>>null

No comments:

Post a Comment