java – uses unchecked or unsafe operations

java – uses unchecked or unsafe operations

The uses unsafe or unchecked operations warning is displayed when you execute code which the Java compiler considers to be lacking in error-checking, or potentially unsafe in some way. However, its a warning, not an error, and will not stop your code from compiling — large projects will often churn out warning after warning, and youre free to determine whether theyre worth taking action on or not. If you want to dig deeper into whats causing the warning to trigger, you can recompile your .java file with the syntax javac -Xlint:unchecked, and the compiler will give you more verbose information as to what exactly is causing the error.

In my experience, this warning can often be caused by using something like an ArrayList without specifying the type which it should expect to hold (i.e. using ArrayList a = new ArrayList() rather than ArrayList<String> a = new ArrayList<String>()). The compiler is, in my example case, warning you that your code isnt going to do any checking for you that the values you add to it are any particular type. In a production application, it would likely be good to specify types, but in a test app, youre free to ignore the warnings if youre not concerned about them.

You get an unchecked cast usually when you cast a generic class, for example:

// Here we have unchecked cast warning
ArrayList<String> arr = (ArrayList<String>) obj;// obj is of type Object

one way to prevent this and make the cast safe is to extend the type which is cast and then use your custom type which extends that like this:

// your class extends generic but is not generic
class MyClass extends ArrayList<String> {  }

//then change your cast like this: 
MyClass arr = (MyClass) obj;//here we have NO warning for unchecked cast

java – uses unchecked or unsafe operations

I fix this problem by updating classpath version in project level gradle files


Leave a Reply

Your email address will not be published.