What causes javac to issue the “uses unchecked or

2018-12-31 06:39发布

For example:

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

8条回答
怪性笑人.
2楼-- · 2018-12-31 07:19

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

查看更多
倾城一夜雪
3楼-- · 2018-12-31 07:24

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<>();
查看更多
登录 后发表回答