Vector3f[] not instance of Object[]

Hey there,

I am trying to make an Array from an ArrayList. I use the .toArray(); method from the ArrayList for that. However, when I run it, the output says Object[] cannot be cast to Vector3f[].

Here’s the code:

        //Convert the list to the array
        Object[] arr = vectorList.toArray();
        vectorArray = (Vector3f[]) arr;

What is wrong?
I did it before, if I remember.

use .toArray(new Vector3f[0])

1 Like

Because it doesn’t cast the object inside the array.
You can’t do it like this

Vector3f[] array = vectorList.toArray(new Vector3f[vectorList.size()]);

To remember this, as a thought experiment what do you suppose would happen if this kind of casting was allowed?

Object[] myArray = new Object[4];
myArray[0] = new Vector3f();
myArray[1] = "My dog has fleas.";
myArray[2] = new JPanel();
myArray[3] = new JLabel();

Vector3f[] vecArray = (Vector3f[])myArray;

…do we really expect Java to check the casting of every element?

No. The answer is that arrays cannot be cast in this way.

And the vectorList doesn’t know that it’s a list of Vector3f’s because of type erasure. The only way it knows what type of array to create is if you tell it by giving it one either as in Ricarrdo’s example where two arrays end up getting created or as in Nehon’s where only one gets created.