0

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

3
  • Integer i = 1 does work, can you show whats not working for you? Commented Nov 15, 2014 at 20:12
  • @SleimanJneidi Presumably they were trying to do TestMap<K, Integer> ... which hides java.lang.Integer. Commented Nov 15, 2014 at 20:13
  • @SleimanJneidi what Radiodef is saying is true. Commented Nov 15, 2014 at 20:44

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is probably a bad idea. See e.g. ibm.com/developerworks/library/j-jtp02216
It works. Thanks. Now I can get rid of those pesky (Integer) casts and what not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.