What causes javac to issue the "uses unchecked or unsafe operations" warning What causes javac to issue the "uses unchecked or unsafe operations" warning java java

What causes javac to issue the "uses unchecked or unsafe operations" warning


This comes up in Java 5 and later if you're using collections without type specifiers (e.g., Arraylist() instead of ArrayList<String>()). It means that the compiler can't check that you're using the collection in a type-safe way, using generics.

To get rid of the warning, just be specific about what type of objects you're storing in the collection. So, instead of

List myList = new ArrayList();

use

List<String> myList = new ArrayList<String>();

In Java 7 you can shorten generic instantiation by using Type Inference.

List<String> myList = new ArrayList<>();


If you do what it suggests and recompile with the "-Xlint:unchecked" switch, it will give you more detailed information.

As well as the use of raw types (as described by the other answers), an unchecked cast can also cause the warning.

Once you've compiled with -Xlint, you should be able to rework your code to avoid the warning. This is not always possible, particularly if you are integrating with legacy code that cannot be changed. In this situation, you may decide to suppress the warning in places where you know that the code is correct:

@SuppressWarnings("unchecked")public void myMethod(){    //...}


For Android Studio, you need to add:

allprojects {    gradle.projectsEvaluated {        tasks.withType(JavaCompile) {            options.compilerArgs << "-Xlint:unchecked"        }    }    // ...}

in your project's build.gradle file to know where this error is produced.