gpt4 book ai didi

java - 使用有界通配符推断类型的问题

转载 作者:行者123 更新时间:2023-11-30 08:14:19 25 4
gpt4 key购买 nike

在下面的代码片段中设置 temp2.​​in 的正确方法是什么?为什么代码无法编译?

public class WildCards {
public static void main(String[] args) {
TheBox<Integer> temp1 = new TheBox<Integer>();
temp1.set(10);
TheBox<? extends Number> temp2 = temp1;
temp2.set(1);
}

public static class TheBox<T> {
T in;

public T get() {
return in;
}

public void set(T in) {
this.in = in;
}
}
}

最佳答案

因为您只能使用 temp2 执行由 任何可能的子类参数化的 TheBox 合法执行的操作编号。其中包括尚未编写的 Number 子类。 Integer 只能分配给 Number某些子类,但不能分配给全部。

给予 temp2.​​set 的唯一合法参数是 null。这是因为 null 可以分配给任何东西。

请澄清“设置 temp2.​​in 的正确方法是什么”的含义。用什么方式合适呢?这段代码的预期行为是什么?

关于java - 使用有界通配符推断类型的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29877098/

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