The following code throws a ClassCastException
when I try to get a mapping with my custom Dog
class as the key:
import java.util.TreeMap;
public class testMain {
public static void main(String[] args) {
TreeMap<Dog, String> m = new TreeMap<Dog, String>();
m.put(new Dog("Fido"), "woof");
// this line produces a ClassCastException
String sound = m.get(new Dog("Fido"));
System.out.println(sound);
}
}
The dog class is simply:
public class Dog {
String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
I don't see why TreeMap
would be casting the Dog
class in the first place. Why do I get a ClassCastException when using a custom made class as the key? Any ideas on how to fix this code would be appreciated as well!