Nested Wildcards

Found a fact about unlimited wildcards that annoy me. For instance:

public class Test {
private static final Map<Integer, Map<Integer, String>> someMap = new HashMap<>();

public static void main(String[] args) {
    getSomeMap();
}

static Map<?, Map<?, ?>> getSomeMap() {
    return someMap;  //compilation fails
  }
}

It does not work, although it works with the return type Map<?, ?>or Map<?, Map<Integer, String>>.

Can someone tell me the exact reason? Thanks in advance.


Update

It seems that I understood, and the simplest explanation of this issue (omitting all these complex rules), in my opinion, is the last entry in Capture Conversion ( link ):Capture conversion is not applied recursively.

+4
source share
1 answer

It is important to understand the meaning of wildcard types.

, Map<Integer, Map<Integer, String>> Map<?, ?>, Map<?, ?> , , Map<?, ?>. , Map<?, ?>.

, Map<?, Map<?, ?>>, , . Map<?,?>, , .

, :

Map<?, Map<?, ?>> map=new HashMap<>();
map.put(null, Collections.<String,String>singletonMap("foo", "bar"));
map.put(null, Collections.<Double,Integer>singletonMap(42.0, 1000));
map.put(null, Collections.<Object,Boolean>singletonMap(false, true));

null, put - , , Map<?, ?>: . , null , .

, , Map<Integer, Map<Integer, String>> Map<?, Map<?, ?>> , Map<Integer, String> , , .

, , - , , , , , :

Map<Integer, Map<Integer, String>> someMap = new HashMap<>();
Map<?, ? extends Map<?, ?>> map=someMap;

Map<Integer, String> Map<?, ?>, Map<?, ?>, ? extends Map<?, ?>. String Object. String Object, Map<?,String>, Map<?,Object>, Map<?, ? extends Object> : String , .

, . :

Map<Integer, Map<Integer, String>> someMap = new HashMap<>();
Map<?, Map<?, ?>> map=Collections.unmodifiableMap(someMap);

, unmodifiableMap, , . (.. Map<?, ?>) , , , .

+2

Source: https://habr.com/ru/post/1570865/


All Articles