抱歉,如果标题看起来有点混乱,但是需要一些例子。
假设我有一个带有泛型类型参数的Java类:
具体的编译错误如下:
假设我有一个带有泛型类型参数的Java类:
public class GenericClass<T> {
}
我可以创建一个变量并指定它的类型为Object,同时将泛型参数设置为String
。Java也允许我将这个变量赋值给另一个泛型参数为通配符<?>
类型的变量:
GenericClass<String> stringy = ...
GenericClass<?> generic = stringy; // OK
然而,当使用带有泛型参数的类时,如果将该参数的类型设置为泛型,则不能将该类的对象分配给内部/嵌套参数为通配符类型 <?>
的完全相同类型/泛型化类型:
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
具体的编译错误如下:
Type mismatch: cannot convert from List<GenericClass<String>> to List<GenericClass<?>>
直觉上,我认为这个任务不应该成为一个问题。那么为什么这个任务会成为一个问题呢?