Eliminate unchecked warnings

When you program with generics, you will see many compiler warnings:
unchecked cast warnings, unchecked method invocation warnings, unchecked
generic array creation warnings, and unchecked conversion warnings. The more
experience you acquire with generics, the fewer warnings you’ll get, but don’t
expect newly written code that uses generics to compile cleanly.
Many unchecked warnings are easy to eliminate. For example, suppose you
accidentally write this declaration:
Set<Lark> exaltation = new HashSet();
The compiler will gently remind you what you did wrong:
Venery.java:4: warning: [unchecked] unchecked conversion
found : HashSet, required: Set<Lark>
Set<Lark> exaltation = new HashSet();
^
You can then make the indicated correction, causing the warning to disappear:
Set<Lark> exaltation = new HashSet<Lark>();
Some warnings will be much more difficult to eliminate. This chapter is filled
with examples of such warnings. When you get warnings that require some
thought, persevere! Eliminate every unchecked warning that you can. If you
eliminate all warnings, you are assured that your code is typesafe, which is a very
good thing. It means that you won’t get a ClassCastException at runtime, and it
increases your confidence that your program is behaving as you intended.
If you can’t eliminate a warning, and you can prove that the code that
provoked the warning is typesafe, then (and only then) suppress the warning
with an @SuppressWarnings("unchecked") annotation. If you suppress warnings
without first proving that the code is typesafe, you are only giving yourself a
false sense of security. The code may compile without emitting any warnings, but
it can still throw a ClassCastException at runtime. If, however, you ignore
unchecked warnings that you know to be safe (instead of suppressing them), you
won’t notice when a new warning crops up that represents a real problem. The
new warning will get lost amidst all the false alarms that you didn’t silence.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值