bbholzbb
bbholzbb

Reputation: 1932

Array List<File> to Array File[]

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;

}

Upvotes: 9

Views: 21823

Answers (1)

NPE
NPE

Reputation: 500377

Use:

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

Upvotes: 22

Related Questions