boxed__l
boxed__l

Reputation: 1336

Array Casting Issue

I have the following code:

String []d=new String[]{"y","z"};
Object []ab=d;
d=(String[]) ab;
System.out.println(d[0]);
System.out.println(ab[0]);

as expected returns y twice

But the following code throws a java.lang.ClassCastException (here fileList is an ArrayList<File> object)

File[] loadedFiles=new File[fileList.size()];
Object[] toArray = fileList.toArray();
loadedFiles=(File[]) toArray;
System.out.println(toArray[0]);
System.out.println(loadedFiles[0]);

While the following doesn't throw anything:

loadedFiles=fileList.toArray(new File[0]);

Javadoc 1.5 says (about toArray()):

The returned array will be "safe" in that no references to it are maintained by this collection. (In other words, this method must allocate a new array even if this collection is backed by an array). The caller is thus free to modify the returned array.

So why can't I modify the array type by casting?

Thanks!

Upvotes: 2

Views: 124

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500385

So why can't I modify the array type by casting?

Casting never changes the type of an actual object. It just checks that the reference in question is a reference to an object of an appropriate type, and lets you use that reference "as" the new type.

Now the array that the value of toArray refers to is an Object[], not a File[]. You can verify this yourself by printing out toArray.getClass(). Therefore you can't cast it to a File[].

You can call an overload which takes an array, at which point it will do the right thing:

Object[] toArray = fileList.toArray(new File[0]);

At that point, toArray will refer to an instance of File[], so when you cast it later, all is well.

Upvotes: 10

Related Questions