我有一个名为“listtable”的
ArrayList<Clause>
。由于某些原因,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
}