• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 392
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
 
Sandeep Vaid
Ranch Hand
Posts: 392
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic