WVrock
WVrock

Reputation: 1765

Specific class instead of generics in Java

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

Answers (1)

Radiodef
Radiodef

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

Related Questions