Two Laptop Bag
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashSet" Watch "HashSet" New topic


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: 2398
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:
subject: HashSet
It's not a secret anymore!