Nested wildcards and subtyping. How to understand when types are compatible?

Usually when generic explanations say something like this:

List<?> list = new ArrayList<?>();

This code (above) throws an error because the compiler does not know what type to instantiate.

but

List<Set<?>> list = new ArrayList<Set<?>>();

this (above) compiles well

and this:

List<Set<?>> list = new ArrayList<Set<String>>();

not compiled.

I'm confusing.

Can you clarify the full right not to interfere in these things.

PS

I know that

List<Number> list = new ArrayList<Integer>();

will not compile, and I understand why.

+4
source share
2 answers

OK basically, this question was supposed to understand the difference between the following two statements. According to comment by @DavidWallace ...

// good
Set<?> a_set = new HashSet<String>();

// bad
List<Set<?>> a_list = new LinkedList<Set<String>>();

a_set, . , a_set HashSet<String>.

, a_list, . LinkedList<Set<String>> Set<String> . , , , .

0

" ":

List<Set<?>> list = new ArrayList<Set<String>>();

, :

List<Set<String>> stringSetList = new ArrayList<Set<String>>();
List<Set<?>> list = stringSetList; // compile error!
Set<Integer>() intSet = new HashSet<Integer>();
intSet.add(1);
list.add(intSet); // oops, compiles but...
Set<String> set = strings.get(0);
for (String str : set) { // Boom! ClassCastException
    // expecting Strings, but got an Integer
}
0

All Articles