This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes equals() and hashcode() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals() and hashcode()" Watch "equals() and hashcode()" New topic
Author

equals() and hashcode()

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
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

Joined: Aug 03, 2008
Posts: 9291
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
jQuery in Action, 2nd edition
 
subject: equals() and hashcode()
 
Similar Threads
equals() and hashCode() from Java.Inquisition
A question about hashCode
help understanding .equals.
enums
OCPJP 6 Practice exams, exam 1 q 57 bad/wrong explanation