代码改变世界

Effective Java 24 Eliminate unchecked warnings

2014-03-18 19:34  小郝(Kaibo Hao)  阅读(521)  评论(0编辑  收藏  举报

Note

  1. 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>();

       

  2. 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.
  3. 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;

    }

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