I need to generically process a map containing a list, but can’t get by the compiler warning. It doesn’t make sense why I can generically process the list, but not the map.
From the below code, why does the compiler allow the ‘processList’ method call, but not the call to ‘processMap’?
It doesn’t seem to matter what Java version (I’ve tried up to 19). I can go to total base Java code (< 1.5) without generics, but, this simply makes no sense to me.
import java.util.ArrayList;
import java.util.HashMap;
class A { }
class B extends A { }
class C extends A { }
/**
* <p>Why does the compiler complain about the calls to processMap?</p>
*/
public class GenericsMystery {
public GenericsMystery() {
ArrayList<B> bList = new ArrayList<>();
ArrayList<C> cList = new ArrayList<>();
processList(bList);
processList(cList);
HashMap<String, ArrayList<B>> bMap = new HashMap<>();
HashMap<String, ArrayList<C>> cMap = new HashMap<>();
processMap(bMap);
processMap(cMap);
}
public void processList(ArrayList<? extends A> list) {
}
public void processMap(HashMap<String, ArrayList<? extends A>> map) {
}
}
>Solution :
Adding ? extends in front of the value type for processMap seems to eliminate the compile warning. I believe the real problem is you are changing the entire type of the parameter, to be something that is extending the original Array. You can’t change the inside of the map without actually changing the map type itself.
Edit In other words, try public void processMap(HashMap<String, ? extends ArrayList<? extends A>> map)