我有一个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
}