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

465,102

Solution 1

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

Solution 2

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()
{
    //...
}

Solution 3

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.

Solution 4

This warning means that your code operates on a raw type, recompile the example with the

-Xlint:unchecked 

to get the details

like this:

javac YourFile.java -Xlint:unchecked

Main.java:7: warning: [unchecked] unchecked cast
        clone.mylist = (ArrayList<String>)this.mylist.clone();
                                                           ^
  required: ArrayList<String>
  found:    Object
1 warning

docs.oracle.com talks about it here: http://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html

Solution 5

I had 2 years old classes and some new classes. I solved it in Android Studio as follows:

allprojects {

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

}

In my project build.gradle file (Borzh solution)

And then if some Metheds is left:

@SuppressWarnings("unchecked")
public void myMethod()
{
    //...
}
Share:
465,102
toolbear
Author by

toolbear

Updated on December 10, 2021

Comments

  • toolbear
    toolbear over 2 years

    For example:

    javac Foo.java
    Note: Foo.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.