aspose file tools*
The moose likes Java in General and the fly likes Understanding equals() with hashcode() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Understanding equals() with hashcode()" Watch "Understanding equals() with hashcode()" New topic
Author

Understanding equals() with hashcode()

jaffar hussain
Greenhorn

Joined: Jun 01, 2012
Posts: 2

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

Joined: Apr 06, 2010
Posts: 4490
    
    8

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

Joined: Jun 01, 2012
Posts: 2

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

Joined: Apr 06, 2010
Posts: 4490
    
    8

You're welcome!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Understanding equals() with hashcode()