Sorry if the title seems confusing, but some examples are in order.
Let's say I have some Java class with a generic type parameter:
public class GenericClass<T> {
}
I can create a variable typed to store an object, with the generic parameter set to, say a String
. Java will also let me assign that variable to another variable but with the generic parameter set to the wildcard <?>
type:
GenericClass<String> stringy = ...
GenericClass<?> generic = stringy; // OK
However, when working with a class with a generic parameter, if you set the type of that parameter to be generic, you can't then assign an object of that class to an identically typed/genericized type where the latter (inner/nested) parameter is of the wildcard type <?>
:
GenericClass<GenericClass<String>> stringy = ...
GenericClass<GenericClass<?>> generic = stringy; // Compile Error
// And just in case that is confusing, a more
// realistic example involving Collections:
List<GenericClass<String>> stringy = ...
List<GenericClass<?>> generic = stringy; // Compile Error
The specific compile error is:
Type mismatch: cannot convert from List<GenericClass<String>> to List<GenericClass<?>>
Intuitively I would think that the assignment in question should not be a problem. So why is this assignment an problem?