抱歉,如果标题看起来令人困惑,但有一些示例是有序的。
假设我有一些带有泛型类型参数的 Java 类:
public class GenericClass<T> {
}
我可以创建一个类型化的变量来存储对象,并将通用参数设置为,比如说String
。 Java 还允许我将该变量分配给另一个变量,但将通用参数设置为通配符<?>
type:
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<?>
是(再次协方差)。在这种情况下,您只能通过 List 进行枚举并期望GenericClass<?>
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)