Monday 24 March 2014

hashCode() : Get the hashCode of an Object

public int hashCode()
Returns a hash code value for the object. This method is used in construction of  HashMap.

By default, Java converts the internal address of the object into an integer and return it as hash code for an object.

If two objects are equal by equals method then they must have same hash code.

If two objects are different, then the hash code for the two objects need not be different But Different hash codes for different objects improve the performance.

class GetHashCode{
 public static void main(String args[]){
  GetHashCode obj1 = new GetHashCode();
  GetHashCode obj2 = new GetHashCode();
  
  System.out.println("Hash Code for the object obj1 is " + obj1.hashCode());
  System.out.println("Hash Code for the object obj2 is " + obj2.hashCode());
  
  obj2 = obj1;
  
  System.out.println("Hash Code for the object obj1 is " + obj1.hashCode());
  System.out.println("Hash Code for the object obj2 is " + obj2.hashCode());
 }
}

Output
Hash Code for the object obj1 is 1688614297
Hash Code for the object obj2 is 1544094574
Hash Code for the object obj1 is 1688614297
Hash Code for the object obj2 is 1688614297


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment