如何在不使用 @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;
}
我在以下行中收到警告unchecked
:else if(type.equals
最佳答案
警告是因为 clone()
方法返回 Object
,因此编译器不确定该对象是 ArrayList
.
而不是使用 clone()
,我推荐:
使用
new ArrayList<>(consoles)
(这是复制构造函数)。创建一个新的
ArrayList<item>
并使用addAll
将项目复制到新的ArrayList<item>
的方法.
在一个不相关的注释中,而 ArrayList
确实实现了clone()
,请注意,并非所有类都可以这样做,因此clone()
可能不起作用。
关于java - 摆脱警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23857897/