Common wildcards in complex types

I do not understand the general boundies pattern . ussage. Could you explain why it processListworks very well and processMapfails with a compilation error in the following example? How to change the signature processMapso that it works both with Map<String, List<String>>andMap<String, List<Object>>

public void processList(List<? extends Object> list) {
}

public void processMap(Map<String, List<? extends Object>> map) {
}

public void f() {
    List<String> list = new ArrayList<>();
    Map<String, List<String>> map = new HashMap<>();

    processList(list); // OK
    processMap(map); // ERROR
}

When moving the generic type definition from the type of the method argument to the paramether method did the trick

public void processMap(Map<String, List<? extends Object>> map)
public <T extends Object> void processMap(Map<String, List<T>> map)

Now I would like to know the difference between the two. Moved to another thread .

+4
source share
3 answers

You can make it work if you eliminate the pattern. That is, you create a generic function with a named type:<T extends Object>

public <T extends Object> void processMap(Map<String, List<T>> map) {
}

public void processList(List<? extends Object> list) {
}

public void f() {
    List<String> list = new ArrayList<>();
    Map<String, List<String>> map = new HashMap<>();

    processList(list); // OK
    processMap(map); // OK now
    processMap(new HashMap<String, List<Integer>>()); // this is OK too
}

, , .

+1

: .

: , ; ? .

public <T> void processMap(Map<String, List<T>> map) {
}

public void f() {
    Map<String, List<String>> map = new HashMap<>();
    processMap(map);
    Map<String, List<Object>> map2 = new HashMap<>();
    processMap(map2);
}
+1
Map<String, List<? extends Object>> map = new HashMap<>();

make the above change in f () method and it works. The Java compiler checks the type of the variable, so both must be the same, I could be wrong.

0
source

All Articles