Ok, I have heard from many places and sources that whenever I override the equals() method, I need to override the hashCode() method as well. But consider the following piece of code
package test;
public class MyCustomObject {
int intVal1;
int intVal2;
public MyCustomObject(int val1, int val2){
intVal1 = val1;
intVal2 = val2;
}
public boolean equals(Object obj){
return (((MyCustomObject)obj).intVal1 == this.intVal1) &&
(((MyCustomObject)obj).intVal2 == this.intVal2);
}
public static void main(String a[]){
MyCustomObject m1 = new MyCustomObject(3,5);
MyCustomObject m2 = new MyCustomObject(3,5);
MyCustomObject m3 = new MyCustomObject(4,5);
System.out.println(m1.equals(m2));
System.out.println(m1.equals(m3));
}
}
Here the output is true, false exactly the way I want it to be and I dont care of overriding the hashCode() method at all. This means that hashCode() overriding is an option rather being a mandatory one as everyone says.
I want a second confirmation.
Because HashMap/Hashtable will lookup object by hashCode() first.
If they are not the same, hashmap will assert object are not the same and return not exists in the map.
The reason why you need to
@Override
neither or both, is because of the way they interrelate with the rest of the API.You'll find that if you put
m1
into aHashSet<MyCustomObject>
, then it doesn'tcontains(m2)
. This is inconsistent behavior and can cause a lot of bugs and chaos.The Java library has tons of functionalities. In order to make them work for you, you need to play by the rules, and making sure that
equals
andhashCode
are consistent is one of the most important ones.It is primarily important when searching for an object using its hashCode() value in a collection (i.e. HashMap, HashSet, etc.). Each object returns a different hashCode() value therefore you must override this method to consistently generate a hashCode value based on the state of the object to help the Collections algorithm locate values on the hash table.
Most of the other comments already gave you the answer: you need to do it because there are collections (ie: HashSet, HashMap) that uses hashCode as an optimization to "index" object instances, an those optimizations expects that if:
a.equals(b)
==>a.hashCode() == b.hashCode()
(NOTE that the inverse doesn't hold).But as an additional information you can do this exercise:
The do this:
What you learn from this example is that implementing
equals
orhashCode
with properties that can be changed (mutable) is a really bad idea.It works for you because your code does not use any functionality (HashMap, HashTable) which needs the
hashCode()
API.However, you don't know whether your class (presumably not written as a one-off) will be later called in a code that does indeed use its objects as hash key, in which case things will be affected.
As per the documentation for Object class: