java - Java 中未经检查的强制转换警告

标签 java casting warnings

Eclipse 说:Type safety: Unchecked cast from Object to ObjectArrayList<Car>当我这样做时:

final ObjectArrayList<Car> icars = (ObjectArrayList<Car>) cars[i];

哪里cars定义为:

final Object[] cars = new Object[1000];
for (int i = 0; i < 1000; i++) {
    cars[i] = new ObjectArrayList<Car>();
}

Eclipse 建议添加 @SuppressWarnings("unchecked")icars目的。但是我在某处读到 Java 不推荐使用注释,所以我应该保持原样吗?

最佳答案

警告只是警告您 cars 中的对象正在转换的数组不能保证是 ObjectArrayList<Car> .

事实证明,Java 不允许使用泛型类型声明数组,除非它们是无界的(请参阅 Java 1.6: Creating an array of List 或此错误报告 6229728 : Allow special cases of generic array creation)。但是如果您可以像这样声明数组,您就不会收到警告:

final ObjectArrayList<Car>[] cars=new ObjectArrayList<Car>[1000]; // not allowed

如果您真的想避免未经检查的转换,您应该使用强类型集合而不是数组(例如,List<ObjectArrayList<Car>>)。

@SuppressWarnings("unchecked") 注释只会告诉编译器不要显示警告。我不建议使用它,除非警告真的让你烦恼。事实上,您将进行未经检查的强制转换(如果您确定数组中元素的类型,这不是问题)。

作为旁注,在 Java 中并没有以任何方式弃用注释。实际上,它们似乎会在 Java 8 中变得更强大(似乎它们会支持 JSR 308: Annotations on Java Types )。也许你读过 @Deprecated 而是一个注解。

关于java - Java 中未经检查的强制转换警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16334944/

相关文章:

java - 在 Veloeclipse 中如何更改 JavaScript 内容的颜色?

Java: mytextarea.setText ("hello") + Thread.sleep(1000) = 奇怪的结果

c - "Pointer from integer/integer from pointer without a cast"问题

c - 警告 : format ‘%d’ expects argument of type ‘int’ , 但参数 3 的类型为 ‘int *’

ios - 将应用程序从 iOS 5.1 更新到 6.0 - 新警告?

java - 当按值排序时,compareTo 将 10 设置在 2 之前

java - JMSWMQ2020 : Failed to connect to queue manager

java - 为什么这个不会投?

java - 如何避免在子类中强制转换父级字段

python-3.x - 在电池jupyter笔记本中关闭警告