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/