I have a HashMap where the values are ArrayLists, and I'm trying to write a function to accept generic instances of these HashMaps
HashMap<String, ArrayList<Integer>> myMap = new HashMap<String, ArrayList<Integer>>();
public static void foo(HashMap<?, ArrayList<?>> a) {}
public static void bar(HashMap<?, ? extends ArrayList<?>> a) {}
// Compilation Failure!
foo(myMap);
// This works, but why do I need ? extends ArrayList
bar(myMap)
The error message is
The method
foo(HashMap<?,ArrayList<?>>)
in the typeExample
is not applicable for the arguments (HashMap<String,ArrayList<Integer>>
).
Why do I need to have a wildcard for the extends ArrayList?
I thought that by having ArrayList<?>
(without the ? extends
), I could restrict the function to only HashMaps with ArrayList values.
I also know that the following generic method works:
public static <K,V> void printer(HashMap<K, ArrayList<V>> list) { }
Which behaves how I thought ArrayList<?>
would work. Can someone explain the subtleties here?