gpt4 book ai didi

java - 为什么不能将包含泛型类型的泛型类型分配给通配符类型的泛型类型类

转载 作者:行者123 更新时间:2023-12-01 04:30:00 25 4
gpt4 key购买 nike

很抱歉,如果标题看起来令人困惑,但一些示例是有序的。

假设我有一些带有泛型类型参数的 Java 类:

public class GenericClass<T> {
}

我可以创建一个类型化的变量来存储对象,并将通用参数设置为 String 。 Java 还允许我将该变量分配给另一个变量,但将通用参数设置为通配符 <?>类型:

GenericClass<String> stringy = ...
GenericClass<?> generic = stringy; // OK

但是,当使用具有泛型参数的类时,如果将该参数的类型设置为泛型,则无法将该类的对象分配给相同类型/泛型类型,其中后者(内部)/nested) 参数为通配符类型 <?> :

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<?>>

直觉上我认为所讨论的作业应该不是问题。那么为什么这个作业会出现问题呢?

最佳答案

您面临的问题被命名为 Covariance .

List<GenericClass<String>> stringy = ...
List<GenericClass<?>> generic = stringy;
generic.add(new GenericClass<Integer>());

如果这不是编译错误,那么最后一行代码是可能的。

您可以通过执行以下操作来解决该错误:

 List<? extends GenericClass<?>> generic = stringy;

但你不能使用add还因为你真的不知道什么? extends GenericClass<?>是(再次协方差)。在这种情况下,您只能通过列表进行枚举并期望 GenericClass<?> .

关于java - 为什么不能将包含泛型类型的泛型类型分配给通配符类型的泛型类型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com