- Forgetting to override
hashcode()
along with theequals()
method or vice versa. - Not overriding
equals()
andhashcode()
when using hash collections likeHashSet
. - Returning a constant value in the
hashcode()
method instead of returning a unique code per object. - Using
==
andequals
interchangeably. The==
comparesObject
references, whereasequals()
compares object values.
What to remember about equals() and hashcode()
- It’s a good practice to always override
equals()
andhashcode()
methods in your POJOs. - Use an effective algorithm to generate a unique hashcode.
- When overriding the
equals()
method, always override thehashcode()
method as well. - The
equals()
method should compare the whole state of objects: values from fields. - The
hashcode()
method could be the ID of a POJO. - When the result of comparing two object's hashcodes is false, the
equals()
method should also be false. - If
equals()
andhashcode()
are not overridden when using hash collections, the collection will have duplicate elements.
Learn more about Java
- Get more quick code tips: Read all of Rafael's articles in the InfoWorld Java Challengers series.
- Check out the videos in Rafael's Java Challengers video playlist.
- Find even more Java Challengers on Rafael's Java Challengers blog and in his book, with more than 70 code challenges.
This story, "Comparing Java objects with equals() and hashcode() " was originally published by JavaWorld.