Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

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.
 
These are not the droids you are looking for. Perhaps I can interest you in a tiny ad?
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic