Instance of your class will be also HashMap so you don't need to, or even shouldn't add another field just to support getOrAdd
method because other inherited and not overridden methods will not be referring to map
field but to this
instance.
So instead of adding separate field
private HashMap<K, List<V>> map;
change extending type of your ListMap
to
public class ListMap<K, V> extends HashMap<K, List<V>>
^^^^^^^
and change your getOrAdd
method to not use map
field but this
public List<V> getOrAdd(K key) {
if (containsKey(key)) {
return get(key);
} else {
List<V> l = new ArrayList<V>();
put(key, l);
return l;
}
}
This change will let you use your map like
ListMap<Integer, String> listMap = new ListMap<Integer, String>();
for (Map.Entry<Integer, List<String>> entry : listMap.entrySet()) {
List<String> val = entry.getValue();//NO CASTING NEEDED
}