gpt4 book ai didi

java - toArray() 与 toArray(new Object[0])

转载 作者:行者123 更新时间:2023-11-30 03:42:12 28 4
gpt4 key购买 nike

我有一个ArrayList<Clause>listtable 。由于某种原因Clause[] whatever = listtable.toArray()给出不兼容的类型错误,但 Clause[] whatever = listtable.toArray(new Clause[0])工作得很好。为什么会这样呢?这两个调用有什么区别? javadoc 说它们“功能相同”。

这是我的完整代码(相关语句就在结束之前):

public static Clause[] readCNF(String name,Boolean print) throws IOException 
{
BufferedReader file = new BufferedReader(new FileReader("./" + name));

ArrayList<Clause> listtable = new ArrayList<Clause>();
String line = null;
while ((line = file.readLine()) != null) {

if(line.charAt(0) == 'p')
{
Scanner scanner = new Scanner(line);
scanner.next(); scanner.next(); Clause.NumVars = scanner.nextInt(); Clause.NumClauses = scanner.nextInt();

} else if(line.charAt(0) != 'c') {

ArrayList<Integer> lits = new ArrayList<Integer>();
Scanner scanner = new Scanner(line);

while(scanner.hasNext())
{
int var = scanner.nextInt();
if(var != 0){ lits.add(var);}
}

listtable.add(new Clause(lits));

}
}

if(print) {
for(Clause clause : listtable)
{
clause.print();
}
}

return(listtable.toArray(new Clause[0])); //since the return type is Clause[] this is the same as the statements in the question
}

最佳答案

toArray() 返回一个 Object 数组。您必须将数组的每个元素转换为您想要的类型。

toArray(T[]) 接受泛型类型并返回特定类型的数组。无需转换返回值和/或数组元素。

正如上面的评论所述,toArray() 方法是预泛型的。

    List<String> list = new ArrayList<String>();
list.add("Alice");
list.add("Bob");

String[] strArray = list.toArray(new String[0]);
for (String str : strArray) {
System.out.println(str);
}

Object[] objArray = list.toArray();
for (Object obj : objArray) {
String str = (String) obj;
System.out.println(str);
}

关于java - toArray() 与 toArray(new Object[0]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26579506/

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