`
michaelljx
  • 浏览: 8850 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

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.

分享到:
评论
1 楼 endual 2012-03-03  
以前也写过英语博客,一边用软件翻译,一边修改复制粘贴。呵呵。

相关推荐

Global site tag (gtag.js) - Google Analytics