This week's book giveaway is in the Agile forum.
We're giving away four copies of The Software Craftsman and have Sandro Mancuso 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 The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "equals() and hashcode()" Watch "equals() and hashcode()" New topic

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

Joined: Aug 03, 2008
Posts: 9327

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
Have you tried LearnNowOnline?
subject: equals() and hashcode()