This code is from Kathy Sierra book SCJP6 page585. I tried this code and it is also working, but the application of the behavior of HashMaps, (which says that, "if the key used to generate hash code is altered then the object cannot be picked back from the Map") in this program is puzzling me big time.
According to my understanding here we are in #1, trying to extract value on basis of dog object whose name is "magnolia". Since the key is generated using dog object with "clover" as name, therefore the hashcodes mismatches and we get null.
In 2nd case we do the same but with clover as name of dog object, but this time the hashcodes matches and equals() also satisfies, and we get the dog key.
But what is happening in Case 3,confuses me:
here though in #3 we assign arthur to d1'sname instance variable but in #4 we are passing a dog object with clover as name.
So ideally the hashcodes should match + equals should return true. So the output should have been dog key like in case 2.
But I dont understand why is this not happening and why we get null???
I am sure that this is the correct behavior and output, but then can you tell me where exactly I am getting wrong with my logic???
All the extra code which was not related to your problem was making it difficult to understand your problem so I removed it. Now at line 4, you are getting null because the when you call m.get(new Dog("clover")), the hashCode will match but the equals method will not return true as d1.name is "arthur" and we are passing it a dog with the name "clover"...
Also if you search the forum, there have been discussions in the past about this question like here, here, here, here ......... See if you get your answer there...
Joined: Nov 10, 2009
Ankit Garg wrote:Also if you search the forum, there have been discussions in the past about this question like here, here, here, here ......... See if you get your answer there...
The first link cleared my doubt and its now clear to me now....
In few days I will write my interpretation of this concept( i dont have time to write it now as I have other studies to do), please verify it then.