我有一个叫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
}发布于 2014-10-27 08:18:44
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);
}https://stackoverflow.com/questions/26579506
复制相似问题