If I define a Map<K,V> map = new HashMap<K, V>() why can’t I do something like:
map.put(new MyKey<CustomObject>(), new SomeOtherObject<CustomObject>());
But if I do it via another method it works i.e.:
add(new MyKey<CustomObject>(), new SomeOtherObject<CustomObject>());
public <K, V> void add(K k, V v){
Map<K, V> threadLocalMap = new HashMap<K, V>();
threadLocalMap.put(k, v);
}
You need to explicitly declare the types used in your map:
In your second example, the
addmethod is generic, so when you call it, K and V are replaced by the actual type used in the calling code.EDIT
You seem to misunderstand the meaning of
Map<K, V>. K and V don’t have any specific meaning, they just show that you can “parameterize” the map to only accept a certain type of key and a certain type of value. But it is your responsibility to define those types.In your first example, you want to use
MyKeyas the type for the keys (theK) andSomeOtherObjectfor the values (theV). So you need to create a specific map for those types:Map<MyKey,SomeOtherObject> map = new HashMap<MyKey, SomeOtherObject>();.You can’t simply write
Map<K, V>because K and V don’t mean anything to the compiler (unless you have create a class called K and a class called V, but I assume you haven’t).In your second example, you use a generic method which takes two parameters of type K and V. When the method is called, the K and the V are replace by the actual types received, so the code in your example is transformed to something very similar to the code at the top of my answer.
I hope this clarifies things. I suggest that you spend time reading a tutorial on generics and look at concrete examples.