• Post Reply Bookmark Topic Watch Topic
  • New Topic

To compare the objects, overriding the hashCode() method is required?  RSS feed

 
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I didn't understand the use of hashCode() for just comparing the objects.
I think to just compare the objects, overriding the equals() method is enough and no need to override the hashCode() method.
But If we want to store those objects in side HashSet and HashMap, overriding of both equals() and hashCode() is required.

Is that my understanding correct? or If not, please explain me the use of hashCode() to just compare the objects.

Appreciate your help.
 
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no excuse for not spending few minutes max it would take to follow Joshua Bloch's recipe for hashCode or fill in the parameter list to a call to either java.util.Arrays.hashCode or java.util.Arrays.deepHashCode. If you're really lazy, there's com.google.common.base.Objects.hashCode()
 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want just to test equality of objects then yes, technically hashCode is unnecessary.
However, overriding equals without overriding hashCode violates the contracts of both methods and should be avoided.

Junilu Lacar wrote: If you're really lazy (...)

If OP is really very lazy, why not have an IDE to generate it?
 
jami siva
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!