Look at this short class.
What does it do? It is a HashMap where the key is a Class object and the value is a Hashmap with key and value of the type which is defined by the Class object.
Say you want to have a method add(K obj), that will be a convenience method. Why would you force a user to type add(Person.class, personInstance), when you can also let him just pass you the instance itself - the code should be able to take the class of the object and put the instance under the key being the class of the object. But I can't. The add(K obj) convenience method does not compile:
public class TypedHashmap extends HashMap<Class, HashMap> {
public <K> HashMap<K, K> getHashMap(Class<K> type) {
return (HashMap<K, K>) getOrDefault(type, new HashMap<K, K>());
}
public <K> void add(K obj, Class<K> type) {
HashMap<K, K> toModify = getHashMap(type);
toModify.put(obj, obj);
}
public <K> void add(K obj) {
add(obj, obj.getClass());
}
}
The compile error:
I can see that Java is not sure about obj.getClass() type. But I do not see why. Is it because it cannot ensure that the class is not actually something extending the K? What is the problem here? Can this be somehow worked around?