PalSivertsen
PalSivertsen

Reputation: 394

Casting Object to Object[][]

I need to cast an object into a multidimensional array but can't figure out how to do it. The object might contain an array of any object (boolean[][], int[][], String[][] etc). Here is a sample code:

public static void main(String[] args) {
    boolean[][] b = new boolean[10][10];

    Object o = b;

    Object[][] multiArray = (Object[][])o;

    for(int i = 0; i < multiArray.length; i++) {
        for(int j = 0; j < multiArray[i].length; j++) {
            // Do something
        }
    }
}

Upvotes: 2

Views: 986

Answers (4)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236004

Try this, noticing that the array of primitive boolean was replaced by an array of Boolean (same consideration for the other data types, e.g.: use Integer in place of int, etc.), which are object types and can be casted to Object:

public static void main(String[] args) {

    Boolean[][] b = new Boolean[10][10];
    // fill b with values

    Object[][] multiArray = new Object[10][10];

    for(int i = 0; i < multiArray.length; i++) {
        for(int j = 0; j < multiArray[i].length; j++) {
            multiArray[i][j] = b[i][j]; // no cast is needed
        }
    }

}

Upvotes: 1

Chris
Chris

Reputation: 5654

Convert boolean to Boolean. Java can then cast Boolean to Object for you (as subclass and super class)

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

You cannot do that. A boolean is a primitive, not a reference type. So while an array (or multi-dimensional array) of boolean values is itself an Object, it's elements are still boolean values, not instances of Object.

If you want to have an array of objects, you would need to box the boolean values as Boolean objects.

Note that you can still write your code with loops without boxing:

for(int i = 0; i < b.length; i++) {
    for(int j = 0; j < b[i].length; j++) {
        // Do something with b[i][j] as a boolean
    }
}

Upvotes: 3

zw324
zw324

Reputation: 27180

boolean[][] is an array of primitives, thus although arrays are covariant, since a boolean is not an Object, it gives you an error telling you the cast is illegal. You might want to use Boolean[][]. Also note that unboxing and boxing does not work on arrays.

Upvotes: 4

Related Questions