2011-03-12 34 views
1

到文件I写的下一段代码:试图垂头丧气对象在Java

private ArrayList<File> filter() { 

    ArrayList<File> result = _filters.get(0).buildTree(_dir.listFiles()); 

    for (int i=1; i<_filters.size(); i++){ 
     File[] tempDir = result.toArray(); 
     result = _filters.get(0).buildTree(tempDir); 
    } 

    return result; 

} 

正如你可以看到我有FILE的ArrayList,然后我使用result.toArray它返回和Object []数组但它是之前的文件,所以为什么我不能下载它回到文件,因为我想在循环中的第三行做? 我得到下一个错误:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.io.File; 
at oop.ex1.filescript.Command.filter(Command.java:50) 
at oop.ex1.filescript.Command.run(Command.java:28) 

我的选择是什么?

回答

6

问题是阵列的转换。不带参数的toArray会创建对象数组,因为列表的类型信息在运行时会丢失。

变化

File[] tempDir = result.toArray(); 

File[] tempDir = result.toArray(new File[result.size()]); 
+0

您好感谢!这就是我所需要的 – yotamoo 2011-03-12 13:54:10

+0

太棒了,它对我很有用 – vNext 2018-01-22 10:27:51