• Java
    December 2, 2011

suppressing warnings this month

John Rose
The OpenJDK community just had a nice sprint cleaning up warnings in JDK code. I did my bit; it was fun.

Two questions came up during reviews, one about the equivalence of wildcards and named type parameters, and one about the best way to handle creation of an array of generic element types.

Here's the quick summary of how to write arrays of generics:

@SuppressWarnings("unchecked")  // array creation must have wildcard
List<String>[] lss = (List<String>[]) new List<?>[1];

In the common case where desired type parameter is wild, there is no need to suppress warnings:
List<?>[] lqs = new List<?>[1];
Class<?>[] cs = new Class<?>[1];

Note that every use of @SuppressWarnings should have a comment.
Also, every @SuppressWarnings should be placed on the smallest
possible program element, usually a local variable declaration.

Here's an example of removing a deprecation warning. A typical deprecation warning is:

Foo.java:876: warning: [deprecation] String(byte[],int) in String has been deprecated
String x = new String(new byte[0], 0);

Here a the corresponding fix:
@SuppressWarnings("deprecation")  // String(byte[],int) in String has been deprecated
// and this is actually useful because the fremdish preskittler was exsufflated
String x = new String(new byte[0], 0);

The clarifying comment is a useful way to record any extra information (if known)
why the deprecated method is being used.

Join the discussion

Comments ( 1 )
  • R&eacute;mi Forax Saturday, December 3, 2011

    About the equivalence relations between named parameter types and wildcards. The JLS rule them out because it requires that the two overrides must have the same number of named parameter types. But theoretically, you can override a wildcard with a named parameter.


Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.