在 java 中忽略 warning:unchecked 转换的后果是什么

What is the consequence of ignoring the warning:unchecked conversion in java

我知道为什么我会收到警告(即将原始类型分配给参数化类型),但如果我忽略警告,我并不知道可能的序列是什么。

List list = new ArrayList();           
List<Integer> iList = list;     // warning: unchecked conversion

如果您希望 List 包含一种类型的元素并且它包含不相关类型的元素,则忽略该警告可能会导致 ClassCastException

例如,以下将通过编译(带有警告)并在运行时抛出 ClassCastException

List list = new ArrayList();    
list.add("something");       
List<Integer> iList = list;
Integer i = iList.get(0);

你在运行时得到 ClassCastException。编译器生成的转换可能会在运行时失败。这将违反泛型类型系统提供的基本保证。从字面上看,您的代码不是类型安全的。看看这个。

List list = new ArrayList();           
List<Integer> iList = list;
list.add("wrong");
for (Integer integer : iList) {
    System.out.println(integer);
}

这是您在运行时遇到的错误。

java.lang.String 无法转换为 java.lang.Integer

(唯一的)运行时结果是由于 ClassCastException 直接或间接导致的代码失败1.

另一个后果是,您允许 应该 在编译时检测和更正的错误继续进行测试,并且可能在成本和后果可能更糟的情况下进行生产。

虽然忽略这些警告是个坏主意,但错误地抑制它们可能更糟。

what do you mean by suppressing them incorrectly ?

我的意思是为实际上会导致运行时异常或其他(实际)问题的警告添加 @SuppressWarning 注释。添加 @SuppressWarning 注释只是为了让编译器 "shut up" 是一种危险的习惯。


1 - 例如,如果您抓住并错误地挤压了 ClassCastException!