Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

}
like image 301
bbholzbb Avatar asked Feb 28 '13 17:02

bbholzbb


People also ask

Can ArrayList convert into array?

ArrayLists are resizable arrays and can store elements of type wrapper class objects. Java provides the flexibility of converting ArrayLists to Array and vice versa. 3 ways of conversion - manual conversion using get() method, using Object[] toArray() method, using T[] toArray(T[] arr) method.

Can we convert list into array?

List has a toArray() method which directly converts the contents of any list into an array while retaining the placement of text in the Array as it was in the original list. Here is the algorithm/steps to convert a list to array in java using this built-in library function. Initialize an ArrayList.

Can we convert array to list in Java?

Since List is a part of the Collection package in Java. Therefore the Array can be converted into the List with the help of the Collections. addAll() method.


1 Answers

Use:

File[] fSorted = x.toArray(new File[x.size()]);
like image 184
NPE Avatar answered Sep 21 '22 17:09

NPE