尝试在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[] 数组,但它之前是 File,所以为什么我不能将它向下转换回 File 作为我想在循环的第三行做什么? 我收到下一个错误:
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)
我有什么选择?
i wrote the next piece of code:
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;
}
As you can see i have an ArrayList of FILE, then i use result.toArray which returns and Object[] array but it was File before, so why can't i downcast it back to File as i am trying to do in the 3rd line in the loop?
i get the next error:
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)
What are my options?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于数组的转换。不带参数的 toArray 创建一个对象数组,因为列表的类型信息在运行时会丢失。
更改
为
The problem is the cast of the arrays. toArray without parameters creates an object array because the type information of the list is lost at runtime.
Change
to