[英]Why can't a Generic type containing a Generic type be assigned to a Generic typed class of wildcard type
抱歉,标题似乎令人困惑,但请按顺序排列一些示例。
假设我有一些带有通用类型参数的Java类:
public class GenericClass<T> {
}
我可以创建一个类型为存储对象的变量,并将通用参数设置为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<?>>
凭直觉,我认为所讨论的作业应该不是问题。 那么为什么这个分配有问题呢?
您面临的问题称为协方差 。
List<GenericClass<String>> stringy = ...
List<GenericClass<?>> generic = stringy;
generic.add(new GenericClass<Integer>());
如果这不是编译错误,那么最后一行代码将是可能的。
您可以通过以下方法解决错误:
List<? extends GenericClass<?>> generic = stringy;
但是您也不能使用add
因为您真的不知道什么? extends GenericClass<?>
? extends GenericClass<?>
为(再次是协方差)。 在这种情况下,您只能枚举List并期望GenericClass<?>
。
从技术上讲,这是因为List<GenericClass<String>>
不是List<GenericClass<?>>
的子类型。 为了使其正常工作,您可以执行以下操作
List<? extends GenericClass<?>> generic = stringy
应该可以按预期工作(尽管很丑...)。
例如,请参阅此SO问题以获取更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.