Search code examples
javaarraylistdowncast

Trying to downcast Object to File in java


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?


Solution

  • 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

    File[] tempDir =  result.toArray();
    

    to

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