什么导致javac发出“使用未检查或不安全操作”警告 [英] What causes javac to issue the "uses unchecked or unsafe operations" warning

查看:187
本文介绍了什么导致javac发出“使用未检查或不安全操作”警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

  javac Foo.java 
注意:Foo.java使用未检查或不安全的操作。
注意:使用-Xlint重新编译:取消选中以获取详细信息。这个问题出现在Java 5及更高版本中,如果你在Java 5和更高版本中出现了问题,使用没有类型说明符的集合(例如, Arraylist()而不是 ArrayList< String>())。这意味着编译器无法以类型安全的方式检查您使用的集合,使用泛型



为了摆脱警告,只要具体说明你的对象类型,重新存储在集合中。所以,而不是

  List myList = new ArrayList(); 

使用

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






在Java 7中,您可以缩短通用实例化类型推断 a>。

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


For example:

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

解决方案

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

这篇关于什么导致javac发出“使用未检查或不安全操作”警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆