The following compiles as expected:
List>> list = new ArrayList>>();
list.add(new HashSet>());
list.add(new HashSet>());
The problem is that generics is type invariant.
Consider the simpler example:
- Given that there is a casting conversion from
Animal to Dog (e.g. Dog extends Animal)...
- There is a capture conversion from
List extends Animal> to a List
Now here's what happens in this scenario:
- Given that there is a capture conversion from
Set> to Set...
- There is a capture conversion from
Set extends Set>> to Set>
So if you want a List where you can add a Set>, Set>, etc, then T is NOT Set>, but rather Set extends Set>>.
Related questions
- Can't cast to to unspecific nested type with generics
- Multiple wildcards on a generic methods makes Java compiler (and me!) very confused
- Java Generic List
>
- Any simple way to explain why I cannot do List animals = new ArrayList()?
- What is the difference between and ?
See also
- Java Generics Tutorial
- Generics and Subtyping | Wildcards | More Fun with Wildcards
- Angelika Langer's Java Generics FAQ
- What is a bounded wildcard?
- Which super-subtype relationships exist among instantiations of generic types?