This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes hashCode() and equals() - How it is possible Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "hashCode() and equals() - How it is possible" Watch "hashCode() and equals() - How it is possible" New topic
Author

hashCode() and equals() - How it is possible

Sandeep Vaid
Ranch Hand

Joined: Feb 27, 2006
Posts: 390
In K&B at page 563 :
"Remember that when you use a class that implements Map, any classes that you use as a part of the keys for that map must override the hashCode() and equals() methods. (Well, you only have to override them if you're interested in retrievingstuff from your Map. Seriously, it's legal to use a class that doesn't override equals()and hashCode() as a key in a Map; your code will compile and run, you just won't find your stuff.)"

In the code below : The Cat class doesn't override hashCode() and equals() but still able to retrieve(find) the stuff. It's it a contraction to k&B statement?
wise owen
Ranch Hand

Joined: Feb 02, 2006
Posts: 2023
Sandeep Vaid
Ranch Hand

Joined: Feb 27, 2006
Posts: 390
Can you explain the output of your code.
I think here Object class's hashCode() comes into picture.

Please specify which is your key. The c1 object or it's name variable.

If c1 object is the key, then it's fine as unique key. and as c2 is difference key you got null.
Naveen Zed
Ranch Hand

Joined: Aug 11, 2006
Posts: 61
Here, We want to get the meaningfully equal Cats(c1,c2 are equal in our sense) String that is "A".But this not catching the Cat That have a name as "B",but referring another Cat.So, the Item to the corresponing to the given key is not there(According to JVM),then surely the answar will be null.
Best example given by-- wise owen,Thank you.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: hashCode() and equals() - How it is possible
 
Similar Threads
Using classes as Keys in Map problem
Maps confusion
Collection Example in K&B
equals() and hashCode() required to override for class used in Map key
Doubt in HashMap