• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Understanding equals() with hashcode()

 
Greenhorn
Posts: 2
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am pasting you two code snippets.

1. Implementing hashcode() and equals() with HashSet:



2. Implementing hashcode() and equals() with HashMap:




My Question is :

While debugging with HashSet line by line I am able to find the flow entering into equals method when its get matched with two equal hashcodes.

But while I am debugging with HashMap line by line I am not able to find the flow entering into equals method when its get matched with two equal hashcodes.


So I am unable to understand how and when exactly equals gets called and why its not getting called with HashMap please somebody explain me this?

Or any link or reference to understand this...

Thanks in advance...
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Using HashMap, it's the keys that are compared, not the values. It's quite happy to have lots of entries with the same value, as long as the keys are unique. And you're using a HashMap<Integer, HashCodeTest_HashMap>.

So in your second code the HashMap doesn't care about the equals() and hashCode() methods of HashCodeTest_HashMap, as your keys are all Integers.
 
jaffar hussain
Greenhorn
Posts: 2
Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Matthew Brown wrote:Using HashMap, it's the keys that are compared, not the values. It's quite happy to have lots of entries with the same value, as long as the keys are unique. And you're using a HashMap<Integer, HashCodeTest_HashMap>.

So in your second code the HashMap doesn't care about the equals() and hashCode() methods of HashCodeTest_HashMap, as your keys are all Integers.



Thank you I tried obj1,obj2,obj3 as keys it worked equals got called thank you once again
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're welcome!
reply
    Bookmark Topic Watch Topic
  • New Topic