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

Where in the JLS is the explanation for it to be legal the assignment of a raw type to an unbounded type?

我正在寻找 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 添加任何内容(因此该部分也是安全的)。

你可以从关于赋值的部分开始

https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.1

允许赋值转换

https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2

允许未经检查的转换

https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.9

允许从原始 G 转换为 G<?>,而不会出现警告。