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 Question about 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 "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: 18825
    
  40

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
Sheriff

Joined: Aug 03, 2008
Posts: 9302
    
  17

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://aspose.com/file-tools
 
subject: Question about hashSet