0
点赞
收藏
分享

微信扫一扫

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


 http://stackoverflow.com/questions/197986/what-causes-javac-to-issue-the-uses-unchecked-or-unsafe-operations-warning

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

List myList = new ArrayList();

use

List<String> myList = new ArrayList<String>(); 

List<String> myList = new ArrayList<String>();

 

 

21 down vote

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

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

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

 

 

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 exception because javac is looking for ArrayList<String> foo = new ArrayList<String>();

 

举报

相关推荐

0 条评论