Hi ,
This is a example given in K&B book-
Remember that when you use a class that implements Map, any classes that you
use as a part of the keys for that map must override the hashCode() and equals()
methods.
We get null when we try to get the Cat object as Cat class does not implements hashCode and equals.
But just look at the example below-
import java.util.*;
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(); }
}
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")); // add some key/value pairs
m.put("k2", Pets.DOG);
m.put(Pets.CAT, "CAT key");
Dog d1 = new Dog("clover"); // let's keep this reference
m.put(d1, "Dog key");
Cat c= new Cat();
m.put(c, "Cat key");
System.out.println(m.get("k1")); // #1
String k2 = "k2";
System.out.println(m.get(k2)); // #2
Pets p = Pets.CAT;
System.out.println(m.get(p)); // #3
System.out.println(m.get(d1)); // #4
System.out.println(m.get(c)); // #5
System.out.println(m.size()); // #6
}
}
Now when we try to add a Cat oject c then we are able to get the answer Cat Key. Does it mean that when we say m.get(new Cat()) we pass a new Cat object as the key not the the same key which we had used to add
m.put(new Cat(), "Cat key");.
Can somebody please explain-when Cat does not implement hashCode() then how are we able to get when we use m.get(c).
Thanks.