Array List<File> to Array File[]

21,145

Use:

File[] fSorted = x.toArray(new File[x.size()]);
Share:
21,145
bbholzbb
Author by

bbholzbb

Updated on August 26, 2020

Comments

  • bbholzbb
    bbholzbb over 3 years

    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;
    
    }
    
  • Eng.Fouad
    Eng.Fouad about 11 years
    +1 My self, I prefer Foo[] array = new Foo[list.size()]; list.toArray(array); just for readability :)