The following example is from K & B book,chapter:7,page:563. This example is about equals & hashcode implementation. I am confused about bold text. I got first 2 lines of bold text. But in 3 & 4 line the hashcode succeeds (arthur & clover), but equals does not succeeds. Then after it gives output "Dog key". As I understand hashcode finds right bucket in this example so it gives the value which is in the bucket("Dog key"). So here what equals is doing? May be I am making you guys confuse. But can anyone explain?
In line 1 you changed name to "clover1" so step 1 of finding the right bucket will fail because of hashCode mismatch.
In line 2 you changed name to "arthur" so step 1 of finding the right bucket will succeed.. Here what you are missing.. name has become "arthur" in line 2, so equals() succeed. [ October 11, 2007: Message edited by: Ahmed Yehia ]
The whole example is like below. Now can you explain?
If they're added to the end of MapTest.main(): d1.name = "magnolia"; System.out.println(m.get(d1)); // #1 d1.name = "clover"; System.out.println(m.get(new Dog("clover"))); // #2 d1.name = "arthur"; System.out.println(m.get(new Dog("clover"))); // #3 Remember that the hashcode is equal to the length of the name variable. When you study a problem like this, it can be useful to think of the two stages of retrieval: 1. Use the hashcode() method to find the correct bucket 2. Use the equals() method to find the object in the bucket In the first call to get(), the hashcode is 8 (magnolia) and it should be 6 (clover), so the retrieval fails at step 1 and we get null. In the second call to get(), the hashcodes are both 6, so step 1 succeeds. Once in the correct bucket (the "length of name = 6" bucket), the equals() method is invoked, and since Dog's equals() method compares names, equals() succeeds, and the output is Dog key. In the third invocation of get(), the hashcode test succeeds, but the equals() test fails because arthur is NOT equal to clover. (What happen in third case, they have not written the answer?)
What is the difference in between this two code? Please explain me?
If you run those sentences in that order, the last one outputs null because you have already changed d1.name. By that point, for the element "Dog key", the instance of Dog2 that maps to it has the name "arthur". So, the new Dog2("clover") will find the right bucket but will fail to find the name, as per the definition of equals() in Dog2.
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop