Generics of generics and more generic <?> assignments

generics, java

Solution

Generics are not covariant in Java. This question may help you:

java generics covariance

Problem

Sometimes I just don't get generics. I often use the most generic version of the collections in the code. For instance if I need a set of just anything I would write something like: ``` Set<?> set1 = new HashSet<Object>(); ``` It is allowed by the compiler and why shouldn't it - `Set<?>` is a as general as `Set<Object>` (or even more generic..). However if I use "generics of generics" making it "more generic" just doesn't work: ``` Set<Class<?>> singletonSet = new HashSet<Class<Object>>(); // type mismatch ``` What is going on? Why is `Set<Object>` assignable to `Set<?>` and `Set<Class<Object>>` isn't assignable to `Set<Class<?>>`? I always find a way around these kinds of problems but in this case I really want to know why this isn't allowed and not a work-around.

Original source

Related problems