Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Understanding equals() with hashcode()

 
jaffar hussain
Greenhorn
Posts: 2
Java
  • Mark post as helpful
  • send pies
  • 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...
 
Matthew Brown
Bartender
Posts: 4567
8
  • Mark post as helpful
  • send pies
  • 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
  • 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: 4567
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic