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

For example:

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

This question is related to java generics warnings

The answer is


The "unchecked or unsafe operations" warning was added when java added Generics, if I remember correctly. It's usually asking you to be more explicit about types, in one way or another.

For example. the code ArrayList foo = new ArrayList(); triggers that warning because javac is looking for ArrayList<String> foo = new ArrayList<String>();


for example when you call a function that returns Generic Collections and you don't specify the generic parameters yourself.

for a function

List<String> getNames()


List names = obj.getNames();

will generate this error.

To solve it you would just add the parameters

List<String> names = obj.getNames();

The solution would be to use specific type in <> like ArrayList<File>.

example:

File curfolder = new File( "C:\\Users\\username\\Desktop");
File[] file = curfolder.listFiles();
ArrayList filename = Arrays.asList(file);

above code generate warning because ArrayList is not of specific type.

File curfolder = new File( "C:\\Users\\username\\Desktop");
File[] file = curfolder.listFiles();
ArrayList<File> filename = Arrays.asList(file);

above code will do fine. Only change is in third line after ArrayList.


The "unchecked or unsafe operations" warning was added when java added Generics, if I remember correctly. It's usually asking you to be more explicit about types, in one way or another.

For example. the code ArrayList foo = new ArrayList(); triggers that warning because javac is looking for ArrayList<String> foo = new ArrayList<String>();


for example when you call a function that returns Generic Collections and you don't specify the generic parameters yourself.

for a function

List<String> getNames()


List names = obj.getNames();

will generate this error.

To solve it you would just add the parameters

List<String> names = obj.getNames();

I just want to add one example of the kind of unchecked warning I see quite often. If you use classes that implement an interface like Serializable, often you will call methods that return objects of the interface, and not the actual class. If the class being returned must be cast to a type based on generics, you can get this warning.

Here is a brief (and somewhat silly) example to demonstrate:

import java.io.Serializable;

public class SimpleGenericClass<T> implements Serializable {

    public Serializable getInstance() {
        return this;
    }

    // @SuppressWarnings("unchecked")
    public static void main() {

        SimpleGenericClass<String> original = new SimpleGenericClass<String>();

        //  java: unchecked cast
        //    required: SimpleGenericClass<java.lang.String>
        //    found:    java.io.Serializable
        SimpleGenericClass<String> returned =
                (SimpleGenericClass<String>) original.getInstance();
    }
}

getInstance() returns an object that implements Serializable. This must be cast to the actual type, but this is an unchecked cast.


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

The solution would be to use specific type in <> like ArrayList<File>.

example:

File curfolder = new File( "C:\\Users\\username\\Desktop");
File[] file = curfolder.listFiles();
ArrayList filename = Arrays.asList(file);

above code generate warning because ArrayList is not of specific type.

File curfolder = new File( "C:\\Users\\username\\Desktop");
File[] file = curfolder.listFiles();
ArrayList<File> filename = Arrays.asList(file);

above code will do fine. Only change is in third line after ArrayList.


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

The "unchecked or unsafe operations" warning was added when java added Generics, if I remember correctly. It's usually asking you to be more explicit about types, in one way or another.

For example. the code ArrayList foo = new ArrayList(); triggers that warning because javac is looking for ArrayList<String> foo = new ArrayList<String>();


for example when you call a function that returns Generic Collections and you don't specify the generic parameters yourself.

for a function

List<String> getNames()


List names = obj.getNames();

will generate this error.

To solve it you would just add the parameters

List<String> names = obj.getNames();

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.


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


for example when you call a function that returns Generic Collections and you don't specify the generic parameters yourself.

for a function

List<String> getNames()


List names = obj.getNames();

will generate this error.

To solve it you would just add the parameters

List<String> names = obj.getNames();

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

This warning also could be raised due to

new HashMap() or new ArrayList() that is generic type has to be specific otherwise the compiler will generate warning.

Please make sure that if you code contains the following you have to change accordingly

new HashMap() => Map map = new HashMap() new HashMap() => Map map = new HashMap<>()

new ArrayList() => List map = new ArrayList() new ArrayList() => List map = new ArrayList<>()


I have ArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;. Because value is a complex structure (I want to clean JSON), there can happen any combinations on numbers, booleans, strings, arrays. So, I used the solution of @Dan Dyer:

@SuppressWarnings("unchecked")
ArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;

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.


You can keep it in the generic form and write it as:

// list 2 is made generic and can store any type of Object
        ArrayList<Object> list2 = new ArrayList<Object>();

Setting type of ArrayList as Object gives us the advantage to store any type of data. You don't need to use -Xlint or anything else.


I have ArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;. Because value is a complex structure (I want to clean JSON), there can happen any combinations on numbers, booleans, strings, arrays. So, I used the solution of @Dan Dyer:

@SuppressWarnings("unchecked")
ArrayList<Map<String, Object>> items = (ArrayList<Map<String, Object>>) value;

This warning also could be raised due to

new HashMap() or new ArrayList() that is generic type has to be specific otherwise the compiler will generate warning.

Please make sure that if you code contains the following you have to change accordingly

new HashMap() => Map map = new HashMap() new HashMap() => Map map = new HashMap<>()

new ArrayList() => List map = new ArrayList() new ArrayList() => List map = new ArrayList<>()


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


I just want to add one example of the kind of unchecked warning I see quite often. If you use classes that implement an interface like Serializable, often you will call methods that return objects of the interface, and not the actual class. If the class being returned must be cast to a type based on generics, you can get this warning.

Here is a brief (and somewhat silly) example to demonstrate:

import java.io.Serializable;

public class SimpleGenericClass<T> implements Serializable {

    public Serializable getInstance() {
        return this;
    }

    // @SuppressWarnings("unchecked")
    public static void main() {

        SimpleGenericClass<String> original = new SimpleGenericClass<String>();

        //  java: unchecked cast
        //    required: SimpleGenericClass<java.lang.String>
        //    found:    java.io.Serializable
        SimpleGenericClass<String> returned =
                (SimpleGenericClass<String>) original.getInstance();
    }
}

getInstance() returns an object that implements Serializable. This must be cast to the actual type, but this is an unchecked cast.


The "unchecked or unsafe operations" warning was added when java added Generics, if I remember correctly. It's usually asking you to be more explicit about types, in one way or another.

For example. the code ArrayList foo = new ArrayList(); triggers that warning because javac is looking for ArrayList<String> foo = new ArrayList<String>();


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

You can keep it in the generic form and write it as:

// list 2 is made generic and can store any type of Object
        ArrayList<Object> list2 = new ArrayList<Object>();

Setting type of ArrayList as Object gives us the advantage to store any type of data. You don't need to use -Xlint or anything else.


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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to generics

Instantiating a generic type Are these methods thread safe? The given key was not present in the dictionary. Which key? Using Java generics for JPA findAll() query with WHERE clause Using Spring RestTemplate in generic method with generic parameter How to create a generic array? Create a List of primitive int? How to have Java method return generic list of any type? Create a new object from type parameter in generic class What is the "proper" way to cast Hibernate Query.list() to List<Type>?

Examples related to warnings

numpy division with RuntimeWarning: invalid value encountered in double_scalars libpng warning: iCCP: known incorrect sRGB profile How to use _CRT_SECURE_NO_WARNINGS C pointers and arrays: [Warning] assignment makes pointer from integer without a cast Server configuration by allow_url_fopen=0 in IntelliJ IDEA shows errors when using Spring's @Autowired annotation Warning :-Presenting view controllers on detached view controllers is discouraged Data truncated for column? Warning message: In `...` : invalid factor level, NA generated How to suppress warnings globally in an R Script