2013-02-28 35 views
6

Tôi phải tạo một ArrayList thành một "Array File" bình thường [].Array List <File> to Array File []

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

Các Lỗi: Cast Exception

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

Làm thế nào tôi có thể trở lại danh sách x như File [] -list?

-

chức năng của tôi:

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; 

} 
+1

thể trùng lặp của [Convert ArrayList để String \ [\]] (http://stackoverflow.com/questions/5374311/convert-arrayliststring-to-string) – Eric

+1

có thể trùng lặp của [Chuyển đổi danh sách thành mảng trong java] (http://stackoverflow.com/questions/9572795/convert-list-to-array-in-java) –

Trả lời

20

Sử dụng:

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

Điều này đã hiệu quả. Cảm ơn bạn! – bbholzbb

+2

+1 Bản thân tôi, tôi thích 'Foo [] array = new Foo [list.size()]; list.toArray (mảng); 'chỉ để đọc được :) –