Wednesday, August 24, 2016

Hashcode and Equals method


Both methods are declared in Object.java (which is parent for all the java classes)

Below snapshot taken from Object.java file



 public boolean equals(Object o) {  
     return this == o;  
   }  
 public int hashCode() {  
     int lockWord = shadow$_monitor_;  
     final int lockWordMask = 0xC0000000; // Top 2 bits.  
     final int lockWordStateHash = 0x80000000; // Top 2 bits are value 2 (kStateHash).  
     if ((lockWord & lockWordMask) == lockWordStateHash) {  
       return lockWord & ~lockWordMask;  
     }  
     return System.identityHashCode(this);  
   }  


Equals method : To check the equality of the two object
    from the above code , if you are not overriding the equals method, then it will check memory address rather than the object . 

  Assume you have a employee class where emp_id is unique , then you need to override the eqquls like below 


 @Override
 public boolean equals(Object o) {  
     return this.emp_id == o.emp_id;  
   }  



Hashcode method : 
       hashcode method will comes in to the picture , if you are using this class's object  as a key in hashmap.
you no need to override this method if you are not using this class as a key.

Nowadays, modern editor will implement hashcode() for you to get the decent hashcode value.


Ok, now we have seen hashcode and equals method separately.. 
  Now ,Question is , any contract between this two method ...

Contract between the two methods Yes ,  in case two object is equal , then hashcode value should be same.
         if hashcode of the two object is same , then object may or may not be equal.

Well, to understand the above statement , we need to know the internal implementation of the hashmap and how read and write happens.

will talk about the those topic soon. stay tuned.   
         

No comments:

Post a Comment