gpt4 book ai didi

java - 在 JLS 中的哪个位置解释了将原始类型分配给无界类型是合法的?

转载 作者:行者123 更新时间:2023-11-29 07:36:45 26 4
gpt4 key购买 nike

我正在为以下句子寻找合法的 JLS 引用:

Vector<?> vector = PreJava5API.getRawVector();

最佳答案

这是给你的报价(4.8. Raw Types):

The warnings from unchecked conversion cover the dual case, where a generified consumer uses a legacy library. For example, a method of the library has the raw return type Vector, but the consumer assigns the result of the method invocation to a variable of type Vector<String>. This is unsafe, since the raw vector might have had a different element type than String, but is still permitted using unchecked conversion in order to enable interfacing with legacy code. The warning from unchecked conversion indicates that the generified consumer may experience problems from heap pollution at other points in the program.

所以你得到一个警告(不是错误!)

Vector<String> vector = PreJava5API.getRawVector();

这是为了促进与遗留代码的互操作性。

更安全的版本是使用通配符(如您的示例)。有了这些,您在如何使用 vector 方面受到严格限制,从而使其安全,甚至不再需要警告:您所能做的就是拉出 Object(始终有效)。您不能向 vector 添加任何内容(因此该部分也是安全的)。

关于java - 在 JLS 中的哪个位置解释了将原始类型分配给无界类型是合法的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34757089/

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