Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals() and hashcode()

 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read this sentence in K & B , can someone please elaborate this statement ?

"When using HashSet or LinkedHashSet, the objects you add to them must override hashCode(). If they don't override hashCode(), the default Object.hashCode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.

Is it required that whenever we override the hashCode() we should also override equals() ?
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to use objects of any class as elements of a Set or key of a Map, you must override the hashCode and equals method. These two methods are used by these collections to find elements. The statement is opposite of what you are saying, it says that you must override the hashCode method when you override the equals method. Otherwise your equals method might not even get called because HashMap and HashSet use the hashCode method before the equals method to find out equal elements...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic