File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashSet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashSet" Watch "HashSet" New topic
Author

HashSet

Akhil Maharaj
Ranch Hand

Joined: Sep 29, 2007
Posts: 63
All ,

My understanding is that we can not add duplicate objects to HashSets.
In the following code Dog class is provided with equals and hashcode methods so that duplicate dogs should not get added to HashSet . But I am able to add equal objects to HashSet ? What is that I am missing ?

Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Be careful to have the right capitalization in the name of the hashCode method.
Akhil Maharaj
Ranch Hand

Joined: Sep 29, 2007
Posts: 63
Keith ,

Thanks for pointing out the mistake on hashCode / hashcode .
Because of the typo ,Effectively in my code there was no hashCode .
But there was equals method.

In such scenario , How the duplicates are identified . Are the duplicates identified based on equals method or based on default hashCode method ?
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
The Contract says: "If the equals() method returns true, the hashCode() of the two objects must be the same"

Two objects are considered duplicates if they return true using equals() And have the same hashCode.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashSet
 
Similar Threads
Map Doubt
HashMap
Difference between hashCode() and equals()
Equals and HasCode
equals() proper implementation