1

After I converted an ArrayList to an Object[]. I then tried to convert that to an File[] which throws a ClassCastException. When I ran it through the Eclipse debugger, I see that the Object[] contains two File objects.

List<File> list = new ArrayList<File>();
list.add(new File("foo.bar")); list.add(new File("foo.bar.bar"));
Object[] objlist = list.toArray();
File[] flist = (File[]) objlist;

Running this throws the following exception:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.io.File;
at sphinx.file.ResourceGetter.getResources(ResourceGetter.java:37)
at sphinx.test.Test.main(Test.java:13)

Eclipse tells me this:

Name: objlist.[0] Value: java.io.File
Value: objlist.[1] Value: java.io.File

I do not understand why this is happening.

stasiomod
  • 21
  • 3

1 Answers1

2

Try

File[] flist = list.toArray(new File[list.size()]);

OR

File[] flist = list.toArray(new File[]{});

You can't cast Object[] to File[]

Read more at similar post casting Object array to Integer array error

Community
  • 1
  • 1
Braj
  • 44,339
  • 5
  • 51
  • 69