java 强制类型转换告警,Java中未经检查的转换警告

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

final ObjectArrayList icars = (ObjectArrayList) cars[i];

where cars is defined as:

final Object[] cars = new Object[1000];

for (int i = 0; i < 1000; i++) {

cars[i] = new ObjectArrayList();

}

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?

解决方案

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.

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[] cars=new ObjectArrayList[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>).

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值