Java中未经检查的转换警告 [英] Unchecked cast warning in Java
问题描述
Eclipse表示:类型安全性:当我这样做时,未经检查就从Object转换为ObjectArrayList
:
Eclipse says: Type safety: Unchecked cast from Object to ObjectArrayList<Car>
when I do:
final ObjectArrayList<Car> icars = (ObjectArrayList<Car>) cars[i];
其中汽车
的定义为:
final Object[] cars = new Object[1000];
for (int i = 0; i < 1000; i++) {
cars[i] = new ObjectArrayList<Car>();
}
Eclipse建议添加 @SuppressWarnings( unchecked )
到 icars
对象。但是我读过某处Java不推荐使用注释的地方,所以我应该保留它不变吗?
Eclipse suggests to add @SuppressWarnings("unchecked")
to icars
object. But I've read somewhere that annotations are deprecated in Java, so should I leave it as it is?
推荐答案
警告是只是,警告您,不能保证正在投射的 cars
数组中的对象是 ObjectArrayList< Car>
。
The warning is just, well, warning you that the objects in the cars
array that are being casted aren't guaranteed to be an ObjectArrayList<Car>
.
事实证明Java不允许使用泛型类型声明数组,除非它们是无界的(请参见 Java 1.6:创建列表数组,或此错误报告 6229728:允许创建通用数组的特殊情况)。但是如果可以这样声明数组,则不会收到警告:
It turns out Java doesn't allow array declaration with generic types unless they're unbounded (see Java 1.6: Creating an array of List, or this bug report 6229728 : Allow special cases of generic array creation). But if you could declare the array like this, you wouldn't be getting the warning:
final ObjectArrayList<Car>[] cars=new ObjectArrayList<Car>[1000]; // not allowed
如果您确实想避免未经检查的类型,则应使用强类型集合数组(例如, List< ObjectArrayList< Car>>
)。
If you really want to avoid an unchecked cast you should use a strongly typed collection instead of an array (for instance, a List<ObjectArrayList<Car>>
).
= http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/SuppressWarnings.html rel = nofollow noreferrer> @SuppressWarnings( unchecked)
注释只会告诉编译器不要显示警告。除非警告确实使您烦恼,否则我不建议您使用它。现实情况是,您将进行未经检查的强制转换(如果您确定数组中元素的类型,这不是问题)。
The @SuppressWarnings("unchecked")
annotation will just tell the compiler not to show the warning. I wouldn't advice using it unless the warning really annoys you. Reality is you'll be doing an unchecked cast (not a problem if you're certain about the type of the elements in the array).
Java中不建议使用注解。实际上,似乎它们将通过Java 8变得更加强大(似乎它们将支持 JSR 308:关于Java类型的注释)。也许您读到 @deprecated
是注释。
As a side note, annotations aren't in any way deprecated in Java. Actually, it seems they'll become more powerful with Java 8 (it seems they'll support JSR 308: Annotations on Java Types). Maybe you read that @Deprecated
is an annotation instead.
这篇关于Java中未经检查的转换警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!