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.
This is correct. However, if you later (when the shortcut is long forgotten) put it into a Map or Set, things will crash badly.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With