aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about hashSet Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Question about hashSet" Watch "Question about hashSet" New topic
Author

Question about hashSet

Sammy Bill
Ranch Hand

Joined: Dec 29, 2008
Posts: 96


i was expecting this code to return 1 as i overrode equals. but it returned 2?
why is that?

Thanks
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16811
    
  19

i was expecting this code to return 1 as i overrode equals. but it returned 2?
why is that?


The hashing collections require that you to obey the equal() / hashCode() contract. If you override equals, then you should also override hashCode() as well -- as you have the code written, you broke the contract.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9191
    
    2

hashCode method is not overridden. So equals will not get called. So answer will be 2...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Abhi vijay
Ranch Hand

Joined: Sep 16, 2008
Posts: 509
This is because you have not overridden hashCode().
Sammy Bill
Ranch Hand

Joined: Dec 29, 2008
Posts: 96
Thanks

Got it.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Question about hashSet
 
Similar Threads
HashSet: Allow Duplicates
equals & hashcode doubt
Sets (Universal, Subsets, Union)
HashSet Duplicate element ?