Item 24 - Eliminate unchecked warnings

From Effective Java 2/e by Joshua Bloch

Unchecked warnings while using generic

  • unchecked cast warnings
  • unchecked method invocation warnings
  • unchecked generic array creation warnings
  • unchecked conversion warnings

@SuppressWarnings("unchecked") annotation

  • If you can’t eliminate a warning, and you can prove that the code that provoked the warning is type-safe
  • Always use the SuppressWarnings annotation on the smallest scope possible
  • Every time you use an @SuppressWarnings("unchecked") annotation, add a comment saying why it’s safe to do so
// 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;
}

Posted by The Finest Artist