I need some help in understanding the following example from K and B book about getting elements from HashMap
The example is from Chap 7 page 565
Simplified version of the code is below
import java.util.*;
Class Dog {
public Dog(
String n)
{
name =n;
}
String name;
public boolean equals(Object O)
{
if((O instance of Dog) && (((Dog)O).name == name)){
return true;
else
return false;
}
}
public int hashCode()
{return name.length();
}
Class MapTest{
public static void main(String [] args)
{
Map<Object, Object> m = new HashMap<Object, Object>();
Dog d1 = new Dog("Clover");
m.put(d1, "Dog Key");
d1.name ="magnolia"
System.out.println(m.get(d1));////prints null ouput
d1.name ="clover"
System.out.println(new Dog("clover");// prints Dog Key as output
d1.name ="arthur"
System.out.println(new Dog(clover"));// prints nulll
}
}
OUTPUT given is
null
Dog Key
null
My doubt is why is first one printing null? when we changed the key object d1's name to magnolia, it should get reflected in the Map too right?, As I understand it is the reference address of the object that gets stored in the collection(not the object itself). So when hashcode of magnolia is checked it should give 8. and the key object has name as magnolia and its hashcode should match. ??? Am I missing something???
Or, is it that the bucket number where the Object is stored does not change, based on any changes in the key object, once it is stored???