File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Sandeep Vaid
Ranch Hand
Posts: 392
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2023
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Sandeep Vaid
Ranch Hand
Posts: 392
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 61
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic