package always.confusing;
import java.util.HashMap;
import java.util.Map;
class Dog {
public Dog(String n) { name = n; }
public String name;
public boolean equals(Object o) {
if((o instanceof Dog) &&
(((Dog)o).name == name)) {
return true;
} else {
return false;
}
}
public int hashCode() {return name.length(); }
}
public class QustionToaAsk {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Object, Object> m = new HashMap<Object, Object>();
Dog d1 = new Dog("clover");
m.put(d1, "Dog key");
System.out.println("**" + m.get(new Dog("clover")));
d1.name = "magnolia";
System.out.println("state after magnolia");
System.out.println(m.get(new Dog("magnolia")));
System.out.println(m.get(d1)); // #1
System.out.println("**" + m.get(new Dog("clover")));///????????
System.out.println("size:" + m.size());
d1.name = "clover";
System.out.println("\nstate after clover");
System.out.println(m.get(new Dog("clover"))); // #2
System.out.println(m.get(d1));
System.out.println("size:" + m.size());
d1.name = "arthur";
System.out.println("\nstate after arthur");
System.out.println(m.get(new Dog("arthur")));
System.out.println(m.get(d1));
System.out.println("size:" + m.size());
}
}
O/p:
**Dog key
state after magnolia
null
null
**null
size:1
state after clover
Dog key
Dog key
size:1
state after arthur
Dog key
Dog key
size:1
why does 1st set of prints fail to fetch for Dog objects with clover and magnolia content but in other two sets it does as expected?
ie why After trying to change to "magnolia", why next get()(still using proper object ie get(new Dog("clover")))) not able to fetch the value "Dog key"? after changing to equals.. still same output –
//ignore