Monday, 2 January 2017

What is Contradiction between hashcode and equals method in java ?

Know Also : Map / HashMap / LinkedList

Java Super class (java.lang.Object) defines two methods:

  1. public boolean equals(Object obj)
  2. public int hashCode()

hashCode() : HaspMap provides put(k,v) for storing key-value pair and get(k) for retrieving the value on behalf of key.
When put(k,v) is used, it calls hashCode() method to find hash and then this hash is used to find the index/bucket where the element will stored in Map.
Similarly, when get(k) is used to fetch value, again hash and index is calculated, and then it look at that particular index to fetch value.

equals() : equals() method compares two objects equality.As hashCode() method helps in finding the exact index where the key is stored, equals() method helps in finding the right key as there may be more than one key-value pairs stored at particular index.

The Contract between hashCode() and equals() method is :

  1. If two objects are equal, using equals() method , then they must have the same hashcode.
  2. If two objects have the same hash code, they may or may not be equal.

      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



Share this Blog with yours Friends !!

No comments:

Post a Comment