nullromo nullromo - 4 years ago 100
Java Question

Cast Java array of arrays to Java 2D array

I have an object that is of type

Object[]
. All elements of the array are actually
Object[]
objects. So essentially it looks like this

Object[] oneD = {objectArray1, objectArray2, objectArray3, ...}


I want to cast this to an
Object[][]
, like this:

Object[][] twoD = (Object[][])oneD;


but I get compiler errors and
ClassCastException
's.

Is there a (correct) way to do this?

Answer Source

You can't cast between array types - java ain't C, but you can transform one pretty easily:

Object[] oneD = {new Object[]{}, new Object[]{}, ...};
Object[][] twoD = Arrays.stream(oneD).map(Object[].class::cast).toArray(Object[][]::new);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download