admin管理员组文章数量:1596328
Note
-
Eliminate every unchecked warning that you can.
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>();
- If you can't eliminate a warning, and you can prove that the code that provoked the warning is type safe, then (and only then) suppress the warning with an @SuppressWarnings("unchecked") annotation.
-
Always use the Suppress Warnings annotation on the smallest scope possible.
// Adding local variable to reduce scope of @SuppressWarnings
public <T> T[] toArray(T[] a) {
if (a.length < size) {
// This cast is correct because the array we're creating
// is of the same type as the one passed in, which is T[].
@SuppressWarnings("unchecked") T[] result =
(T[]) Arrays.copyOf(elements, size, a.getClass());
return result;
}
System.arraycopy(elements, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
-
Every time you use an @SuppressWarnings("unchecked") annotation, add a comment saying why it's safe to do so.
Summary
Unchecked warnings are important. Don't ignore them. Every unchecked warning represents the potential for a ClassCastException at run-time. Do your best to eliminate these warnings. If you can't eliminate an unchecked warning and you can prove that the code that provoked it is typesafe, suppress the warning with an @SuppressWarnings("unchecked") annotation in the narrowest possible scope. Record the rationale for your decision to suppress the warning in a comment.
转载于:https://wwwblogs/haokaibo/p/eliminate-unchecked-warnings.html
本文标签: JavaEffectivewarningsUncheckedEliminate
版权声明:本文标题:Effective Java 24 Eliminate unchecked warnings 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dianzi/1728256025a1151024.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论