HashCode Method In Object Class

Java Spring Decoded
Javarevisited
Published in
2 min readApr 10, 2023

Often we think why java has the hashcode method associated with it in the Object Class , where do we use it as developers and why we need to overwrite it when we are overriding the equals method ?

There is a contract between hashcode and equals method also :-

  • If two objects are equal according to the equals(Object)
    method, then calling the hashCode method on each of
    the two objects must produce the same integer result.

Lets Consider a scenario , where the contract violates.

Consider below example:-

class MyObject{
String value;

@override
public boolen equals(MyObject obj){
return this.value.equals(obj.value);
}
@override
publis int hashCode(MyObject obj){
Random rand = new Random()
return rand.nextInt(10);
}

}


HashSet<MyObject> set = new HashSet<>();
MyObject obj1 = new MyObject();
obj1.setValue("similar");
MyObject obj2 = new MyObject();
obj1.setValue("similar");
set.add(obj1);
set.add(obj2);


lets closely look the above code , here when we try to add the object to the hashset , it will check first the hashcode for both the object , even though these two objects are equal , both of these will get stored in HashSet as two different keys , resulting in duplicacy of Hashset , As we can see here , Not providing correct hashCode implementation leads to Incorrect behaviour in HashMaps , HashTables , HashSet .

The general contract of hashCode is:

  • During the execution of the application, if hashCode() is invoked more than once on the same Object then it must consistently return the same Integer value, provided no information used in equals(Object) comparison on the Object is modified. It is not necessary that this Integer value to be remained same from one execution of the application to another execution of the same application.
  • If two Objects are equal, according to the equals(Object) method, then hashCode() method must produce the same Integer on each of the two Objects.
  • If two Objects are unequal, according to the equals(Object) method, It is not necessary the Integer value produced by hashCode() method on each of the two Objects will be distinct. It can be same but producing the distinct Integer on each of the two Objects is better for improving the performance of hashing based Collections like HashMap, HashTable…etc.

Related Articles :-

https://medium.com/@javabackend175/equals-method-in-java-34ff82f1180

--

--

Java Spring Decoded
Javarevisited

All Articles related to java , spring , Backend Development and System Design.