使用通配符参数分配相同的通用类型

发布于 2025-02-10 05:43:44 字数 251 浏览 2 评论 0原文

为什么以下方法不给出编译器错误? :

    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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨小墨 2025-02-17 05:43:44

但是,为什么编译器认为L2的静态型与L1相同? ((
因此,没有编译器错误)

,因为它们完全相同。变量的编译时类型l1l2均为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;时,您可以同时进行l1l2指向list&lt; double; double&gt; 。很好。由于l1具有类型列表&lt;?扩展数字&gt;,有时可以指向list&lt; integer&gt;,而在其他时候则指向list&lt; double&gt;。考虑一个更简单的示例:

public void func4(Object o1, Object o2) {
    o1 = o2;
}

我可以将字符串作为第一个参数,而整数作为第二个参数,这很好。分配O1 = O2;将导致o1o2指向Integer对象和o1o2可以做到这一点,因为它们具有对象

but why the compiler thinks the static-type of l2 is the same as l1? (
hence, there's no compiler error )

Because they are exactly the same. The compile-time type of the variables l1 and l2 are both List<? extends Number>.

Run-time error could occur in the method

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 of l1.

since wildcards are used, their types could be anything that inherits
from Number.

I think you are thinking of the fact that, for example, you can pass a List<Integer> as first argument and a List<Double> as second argument. Yes, and that's perfectly fine. Then l1 will point to the List<Integer> and l2 will point to the List<Double>. Then when you do l1 = l2;, you make both l1 and l2 point to the List<Double>. And that's fine. Since l1 has type List<? extends Number>, it can sometimes point to a List<Integer> and at other times point to a List<Double>. Consider a simpler example:

public void func4(Object o1, Object o2) {
    o1 = o2;
}

I can pass a String as first argument and an Integer as second argument, and that's perfectly fine. The assignment o1 = o2; will cause both o1 and o2 to point to the Integer object, and o1 and o2 can do that since they have type Object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文