9

I have to form an ArrayList to an "normal" Array File[].

File[] fSorted = (File[]) x.toArray();

The Error: Cast Exception

Exception in thread "Thread-5" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.io.File;

How can I return the list x as File[ ]-List?

--

My function:

private File[] sortFiles(File[] files){;

    ArrayList<String> allFiles = new ArrayList<String>() ;
    for (int index = 0; index < files.length; index++)  
    {  
        File afile = new File(files[index].toString());
        allFiles.add(afile.getPath().toString());

    } 
    java.util.Collections.sort(allFiles);

    ArrayList<File> x = new ArrayList<File>();
    for(int i = 0; i< allFiles.size(); ++i){
        x.add(new File(allFiles.get(i)));
    }
    File[] fSorted = (File[]) x.toArray();

    return fSorted;

}
2

1 Answer 1

22

Use:

File[] fSorted = x.toArray(new File[x.size()]);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 My self, I prefer Foo[] array = new Foo[list.size()]; list.toArray(array); just for readability :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.