Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need to override hashcode method?

Tags:

java

I was looking at the java.lang.Object and also reading couple of questions in StackOverflow on the same topic.

equals() method is used to determine the equality of two objects.

Basically, if you want to store an object in a collection (Map, Set, List) then you have to implement equals and hashCode methods according to the contract defined in the documentation.

Correct me if i am wrong, If i am not storing my Class inside an collection, then i don't need to over-ride the hashcode method as the equals method would be more than enough.

like image 843
Kevin Avatar asked May 25 '26 15:05

Kevin


2 Answers

This is correct. However, if you later (when the shortcut is long forgotten) put it into a Map or Set, things will crash badly.

like image 128
Henry Avatar answered May 28 '26 05:05

Henry


It is recommended to override hashCode if you are overriding equals but it is not mandatory. This method is supported for the benefit of hash tables such as those provided by HashMap.

Note: So if you are sure that you or anyone else will never use your class object to be stored in a hashed collection then skip it. Otherwise override it.

like image 33
Juned Ahsan Avatar answered May 28 '26 05:05

Juned Ahsan