For example:
javac Foo.java Note: Foo.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
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.
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.
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() { //... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With