wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes HashSet Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "HashSet Problem" Watch "HashSet Problem" New topic
Author

HashSet Problem

garima jain
Ranch Hand

Joined: Sep 22, 2008
Posts: 60

I wrote the above program. Output is true and false. Why for line# 1 output is true. Since Dog class does not implement hashCode and Equals method, Object's class hashCode will be used which returns different no for any input value. So, search in bucket different from where the elementwas stored should lead to element not found. Please tell where I am wrong. Thanks, Garima
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Why for line# 1 output is true. Since Dog class does not implement hashCode and Equals method, Object's class hashCode will be used which returns different no for any input value.


The Object's hashCode() and equals() method is designed to hash on the identity of the object -- meaning you can find the object, if it is the same instance.

And noticed that you used the object referred to by the d1 variable, for both add() and contains(). It is the same object. Hence, true.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
garima jain
Ranch Hand

Joined: Sep 22, 2008
Posts: 60
Thanks Henry, I got it.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: HashSet Problem