Reputation: 1765
How can I extend HashMap with a specific class.
public class TestMap<K, V> extends HashMap<K, V>
I want V to be an Integer. Writing Integer instead of V overrides Integer class and causes bugs(Integer i = 1
does not work) when integer is used. How can I fix this?n
Upvotes: 0
Views: 49
Reputation: 37845
Parameterize the extended class and only declare a type for the key:
class IntegerMap<K> extends HashMap<K, Integer> {}
Then you can do:
IntegerMap<String> integerByString = new IntegerMap<String>();
integerByString.put("0", 0);
integerByString.put("1", 1);
As a side note, if you are actually extending a JDK collection class, it is generally not considered a good style.
Normally you would write a class that controls the Map from the outside:
class MapController<K> {
Map<K, Integer> theMap;
}
Or perhaps a method that prepares it in some way:
static <K> Map<K, Integer> prepMap() {
Map<K, Integer> theMap = new HashMap<>();
return theMap;
}
Upvotes: 4