Java 摆脱警告?
如何在不使用Java 摆脱警告?,java,Java,如何在不使用@SuppressWarnings的情况下消除以下代码中的警告 // consoles is an ArrayList of console. The class console extends the class item. // pcs is an ArrayList of pc. The class pc extends the class item. public static boolean verify(String type, String model) { A
@SuppressWarnings
的情况下消除以下代码中的警告
// consoles is an ArrayList of console. The class console extends the class item.
// pcs is an ArrayList of pc. The class pc extends the class item.
public static boolean verify(String type, String model)
{
ArrayList<item> obj;
if(type == null) return false;
else if(type.equals("console")) obj = (ArrayList<item>) consoles.clone();
else if(type.equals("pc")) obj = (ArrayList<item>) pcs.clone();
else return false;
for(int j = 0; j < obj.size(); j++)
if(obj.get(j).get_model().equals(model))
return true;
return false;
}
//consoles是console的ArrayList。类控制台扩展类项。
//pcs是pc的ArrayList。类pc扩展了类项。
公共静态布尔验证(字符串类型、字符串模型)
{
ArrayList obj;
if(type==null)返回false;
else if(type.equals(“console”))obj=(ArrayList)consoles.clone();
如果(type.equals(“pc”))obj=(ArrayList)pcs.clone();
否则返回false;
对于(int j=0;j
我在以下行中得到了警告:
else if(type.equals
该警告是因为clone()
方法返回一个对象
,因此编译器不确定该对象是否为ArrayList
我建议您不要使用clone()
,而是:
新建ArrayList(控制台)
(这是复制构造函数)ArrayList
,并使用addAll
方法将项目复制到新的ArrayList
另一方面,虽然
ArrayList
确实实现了clone()
,但请注意,并非所有类都可以实现,因此clone()
可能无法工作。警告是因为clone()
方法返回一个对象,因此编译器无法确定该对象是否为ArrayList
我建议您不要使用clone()
,而是:
使用新建ArrayList(控制台)
(这是复制构造函数)
创建新的ArrayList
,并使用addAll
方法将项目复制到新的ArrayList
另一个不相关的注意事项是,ArrayList
确实实现了clone()
,但请注意,并非所有类都可以实现,因此clone()
可能无法工作。“unchecked”是警告,因为clone()是
方法返回对象
,并且不能保证它是数组列表
@saiarcot895:我明白了,谢谢你指出这一点……有没有一种简单的方法可以避免得到它?如果没有@SuppressWarning,你就不能。也许你可以向你的IDE说明它应该显示的警告的严重性阈值。Eclipse有很多在Window->Preferences->Java->Compiler->Errors/Warnings下有许多选项。但是,唯一真正的方法是使用@SuppressWarnings
注释“unchecked”是警告,因为克隆()
方法返回对象
,并且不能保证它是数组列表
@saiarcot895:我明白了,谢谢你指出这一点……有没有一种简单的方法可以避免得到它?如果没有@SuppressWarning,你就不能。也许你可以向你的IDE说明它应该显示的警告的严重性阈值。Eclipse有很多在Window->Preferences->Java->Compiler->Errors/Warnings下有许多选项。但是,唯一真正的方法是使用@SuppressWarnings
注释使用新的ArrayList(控制台)(这是复制构造函数)。
这解决了警告消息。非常感谢使用新的ArrayList(控制台)
(这是复制构造函数)。这解决了警告消息。非常感谢!