This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The above code can be found in K & B book at page no. - 623. I have modified the line 8th as per the code given in the book.
The following was the output found ::
Doubt :: My doubt is on line no. - 8 and 9.
On line no. 7-As per the book says that if we change the value of the object it returns null so, here as we have changed the value to "mangolia" and so the output is null. But if we go to line no. -8 . I am changing the value again to "arthur" which has length equal to 6(which is equal to the length of "clover"), so it'll succeed the hashcode() method but it should fail in equals() method and should return null. But my output is giving "Dog key". Why? Please let me know if am wrong in my understanding.
On line no. 9- The value is changed to "arthur" but to get the key, a new object of type Dog1 with name as "clover" is created. And now here it fails. I didn't get that why we are creating a new object? And if we are assigning it to "clover" then it should succeed and what is the purpose of changing the d1.name="arthur" ? Which two values are now getting compared? That is, "clover"(which is created by new in line no. 8) with "arthur" OR "clover"(which is created by new in line no. 8) with "clover"(Created earlier as d1)??
The original Dog() object shares two references: one is in the HashMap the other is variable d1. So, changing any attribute of reference d1 changes the same object sitting in the HashMap. If you change d1 to d1.name = "magnolia", the same Dog object in the hashMap is now named "magnolia" and not "clover" anymore.
The original Dog object stored in the HashMap previously had a hashCode of 6 ("clover"), and was then changed to "magnolia" (hashCode 8), but the map was never "rehashed". So now, the Dog object with a hashCode of 8 (magnolia) is still sitting in the same hash bucket of 6. If you simply go up to the Dog class and change the implementation of equals() to return a constant value, let's say integer 5, then line 7 will return "Dog Key" instead of null.
Line 9 obviously returns null. Forget about the new Dog object for a minute and understand this: The map will be searched for a Dog object with the name "clover". Because you changed the HashMap's Dog object's name to "arthur" (previous line), the hashcode will match but the equals() will fail and return null.