gpt4 book ai didi

java - 摆脱警告?

转载 作者:行者123 更新时间:2023-12-01 18:31:48 24 4
gpt4 key购买 nike

如何在不使用 @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() ,我推荐:

  1. 使用 new ArrayList<>(consoles) (这是复制构造函数)。

  2. 创建一个新的 ArrayList<item>并使用 addAll将项目复制到新的 ArrayList<item> 的方法.

在一个不相关的注释中,而 ArrayList确实实现了clone() ,请注意,并非所有类都可以这样做,因此clone()可能不起作用。

关于java - 摆脱警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23857897/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com