Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 
like image 449
toolbear Avatar asked Oct 13 '08 15:10

toolbear


People also ask

How do you fix unchecked or unsafe operations?

How to resolve warning message: uses unchecked or unsafe operations. You can resolve this warning message by using generics with Collections. In our example, we should use ArrayList<String> rather than ArrayList() . When you will compile above code, you won't get warning message anymore.

How do I get rid of unchecked cast warning?

If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.


2 Answers

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<>(); 
like image 179
Bill the Lizard Avatar answered Sep 28 '22 02:09

Bill the Lizard


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() {     //... } 
like image 44
Dan Dyer Avatar answered Sep 28 '22 02:09

Dan Dyer