public class Dog {
String name;
public Dog(String name) {
this.name = name;
}
public boolean equals(Object o) {
if ((this == o) && ((Dog) o).name == name) {
return true;
} else {
return false;
}
}
public int hashCode() {
return name.length();
}
}
class Cat {
}
enum Pets {
DOG, CAT, HORSE
}
class MapTest {
public static void main(String[] args) {
Map<Object, Object> m = new HashMap<Object, Object>();
m.put("k1", new Dog("aiko"));
m.put("k2", Pets.DOG);
m.put(Pets.CAT, "CAT Key");
Dog d1 = new Dog("Clover");
m.put(d1, "Dog key");
m.put(new Cat(), "Cat key");
System.out.println(m.get("k1"));
String k2 = "k2";
System.out.println(m.get(k2));
System.out.println(m.get(Pets.CAT));
System.out.println(m.get(d1));
System.out.println(m.get(new Cat()));
// UNABLE TO UNDERSTAND BELOW PART OF CODE
d1.name = "magnolia";
System.out.println(m.get(d1)); // #1 //prints Dog Key
d1.name = "clover";
System.out.println(m.get(new Dog("clover"))); // #2 // prints null
d1.name = "arthur";
System.out.println(m.get(new Dog("clover"))); // #3 // prints null
}
}
I am trying to understand the hashcode() implementation from kathy and berts book for SCJP6. While I have basic understanding of hashcode implementation, a scenario from the book tricked me up and I am confused with the output.
Based on the program above, it says:
- 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.
The above three line talks about length of the name and its relevant hashcode() implementation but how is it comparing the length when get() method is called?