Java Programming Tutorials

Java programming tutorials with many code examples!

Java unchecked warnings

Java unchecked warnings

In this tutorial we’re going to show how to eliminate unchecked warnings that occur frequently when mixing Java Generics with legacy code.

Sometime, when working with pre-generics code (for example old Apache Commons), you may encounter the following warnings:
Unchecked assignment: ‘java.util.List’ to ‘java.util.List<java.lang.String>’

It means that you try to assign not type safe object to a type safe variable. If you are make sure that such assignment is type safe, you can disable the warning using @SuppressWarnings annotation, as in the following examples.

SuppressWarnings on variable declaration

private static List namesFromLibrary() {
    return Arrays.asList("Java", "Clojure");
}

public static void main(String[] args) {
    @SuppressWarnings("unchecked")
    List<String> names = namesFromLibrary();
    System.out.println(names);
}

SuppressWarnings on method

In short methods unchecked warning can be eliminated on method level:

@SuppressWarnings("unchecked")
private static List<String> moreNames() {
    return new ArrayList(Arrays.asList("Bernard", "Witold"));
}

public static void main(String[] args) {
    List<String> moreNames = moreNames();
    System.out.println(moreNames);
}

SuppressWarnings before return statement

@SuppressWarnings cannot be used on return statement, but result can be assigned to a local variable, where the warning can be eliminated:

private static List<String> evenMoreNames() {
    @SuppressWarnings("unchecked")
    ArrayList names = new ArrayList(Arrays.asList("Jon", "Snow"));
    return names;
}

public static void main(String[] args) {
    List<String> evenMoreNames = evenMoreNames();
    System.out.println(evenMoreNames);
}

SuppressWarnings on class

Although it is allowed, this practice is strongly discouraged, because it may eliminate more than one would like to:

@SuppressWarnings("unchecked")
public class UncheckedWarnings {
    // code with unchecked warnings
}

Rule of SuppressWarnings

Use @SuppressWarnings on the narrowest possible scope.

Share with the World!