I have read through several posts on here about this topics.
This was a especially a good post
I thought I understood the PECS-concept, and tried to set up a small example to test it out.
import java.util.Map;
import java.util.HashMap;
class Test {
public static void main(String[] args) {
Map<String, ? super Number> map = new HashMap<>();
map.put("int", 1);
map.put("double", 1.0);
map.put("long", 100000000000L);
print(map);
}
public static void print(Map<String, ? extends Number> map) {
map.forEach((k, v) -> System.out.printf("Key: %s, Val: %s%n", k, v));
}
}
I know I need to use super
to be able to insert multiple subtypes in to the same map.
But when it comes to printing. I thought using extends
would be sufficient, since PECS (Producer extends)
Instead I get this:
Error:(12, 15) java: incompatible types: java.util.Map<java.lang.String,capture#1 of ? super java.lang.Number> cannot be converted to java.util.Map<java.lang.String,? extends java.lang.Number>