使用通配符参数分配相同的通用类型
为什么以下方法不给出编译器错误? :
public void func3(List<? extends Number> l1, List<? extends Number> l2) {
l1 = l2;
}
该方法可能会发生运行时错误,但是为什么编译器认为l2
的静态类型与l1
相同? (因此,没有编译器错误)
Why the following method does not give a compiler error? :
public void func3(List<? extends Number> l1, List<? extends Number> l2) {
l1 = l2;
}
Run-time error could occur in the method, but why the compiler thinks the static-type of l2
is the same as l1
? ( hence, there's no compiler error )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
,因为它们完全相同。变量的编译时类型
l1
和l2
均为list&lt;扩展数字&gt;
。NO中发生,运行时错误不会发生。任务是完全安全的。可以用
l2
的类型指向的任何东西都可以用l1
的类型指出。我认为您正在考虑这样一个事实,例如,您可以将
列表&lt; integer&gt;
作为第一个参数,而list&lt; double&gt;
作为第二个参数。是的,这很好。然后,l1
将指向list&lt; integer&gt;
和l2
将指向list&lt; double&gt;
。然后,当您做l1 = l2;
时,您可以同时进行l1
和l2
指向list&lt; double; double&gt;
。很好。由于l1
具有类型列表&lt;?扩展数字&gt;
,有时可以指向list&lt; integer&gt;
,而在其他时候则指向list&lt; double&gt;
。考虑一个更简单的示例:我可以将
字符串
作为第一个参数,而整数
作为第二个参数,这很好。分配O1 = O2;
将导致o1
和o2
指向Integer
对象和o1
和o2
可以做到这一点,因为它们具有对象
。Because they are exactly the same. The compile-time type of the variables
l1
andl2
are bothList<? extends Number>
.No, runtime error cannot occur. The assignment is completely safe. Anything that can be pointed to by the type of
l2
can be pointed to by the type ofl1
.I think you are thinking of the fact that, for example, you can pass a
List<Integer>
as first argument and aList<Double>
as second argument. Yes, and that's perfectly fine. Thenl1
will point to theList<Integer>
andl2
will point to theList<Double>
. Then when you dol1 = l2;
, you make bothl1
andl2
point to theList<Double>
. And that's fine. Sincel1
has typeList<? extends Number>
, it can sometimes point to aList<Integer>
and at other times point to aList<Double>
. Consider a simpler example:I can pass a
String
as first argument and anInteger
as second argument, and that's perfectly fine. The assignmento1 = o2;
will cause botho1
ando2
to point to theInteger
object, ando1
ando2
can do that since they have typeObject
.