Unchecked cast warning in Java

情到浓时终转凉″ 提交于 2020-01-04 14:08:28

问题


Eclipse says: Type safety: Unchecked cast from Object to ObjectArrayList<Car> when I do:

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

where cars is defined as:

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

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?


回答1:


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>.

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

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>>).

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).

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.




回答2:


If you can't change the Object[] cars to be an ObjectArrayList<Car>[] array, then yes, leave it as it is. The compiler only gives you a warning. When you know that you can cast, then you don't have to listen to what the compiler says.

If you find the Warning annoying, then yes you can add the @SuppressWarnings("unchecked").




回答3:


You defined cars as: Object[] cars so when you try to put a cars element in icars you are casting from Object to ObjectArrayList<Car>.

The compiler can't know if all the elements in cars array are ObjectArrayList<Car>, so it shows the warning

To avoid this you can change the cars array definition to:

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



来源:https://stackoverflow.com/questions/16334944/unchecked-cast-warning-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!