Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
        }
    }
}
like image 998
PalSivertsen Avatar asked Dec 07 '25 23:12

PalSivertsen


1 Answers

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.

like image 87
zw324 Avatar answered Dec 10 '25 11:12

zw324



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!