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;
}
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.
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.
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.
Use:
File[] fSorted = x.toArray(new File[x.size()]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With