toArray()和toArray(new Object[0])的区别

3
我有一个名为“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
    }

1
继续阅读javadoc:返回数组的运行时类型是指定数组的类型。 - Sotirios Delimanolis
但是,如果toArray()方法不起作用,他们为什么还要有这个方法呢? - Elliot Gorokhovsky
1
你说的“它不工作”是什么意思?你有进行类型转换吗?这是安全的类型转换吗?Javadoc中指定的返回类型是什么?它非常好地运行并按预期工作。 - Sotirios Delimanolis
我的意思是,在括号内没有新的Object[0],它就无法编译。 - Elliot Gorokhovsky
1
我相信它是在泛型之前出现的。 - Sotirios Delimanolis
显示剩余3条评论
1个回答

4

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);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接