开发者

The type of an expression must be an array type, but it is resolved to Object

开发者 https://www.devze.com 2023-04-04 02:30 出处:网络
I expected this to compile, but I kept getting the error \"The type of an expression must be an array type, but it is resolved to Object\". Is there a simple workaroun开发者_运维百科d for this?

I expected this to compile, but I kept getting the error "The type of an expression must be an array type, but it is resolved to Object". Is there a simple workaroun开发者_运维百科d for this?

public class NodeTest {
    public static void main(String[] args) {

    Object[] arr = new Object[5]; // each element of object will be an array of integers.
    for(int i = 0; i < 5; i++){
        int[][] a = new int[2*(i+1)][2*(i+1)];
        arr[i] = a;
    }
    arr[0][0][0] = 0; //error here
}

}


arr is Object[] so arr[0] will return an Object

But since you know that arr contains int[][] as instance of Object you will have to cast them to be so.

( ( int[][] ) arr[0] )[0][0] = 0;


You want to declare arr as int[][][] rather than Object[]. While arrays are of type Object so the assignment in the loop is legal, you're then losing that type information so the compiler doesn't know the elements of arr are int[][] in the bottom line.

int[][][] arr = new int[5][][];
for(int i = 0; i < arr.length; i++) { //good practice not to hardcode 5
    arr[i] = new int[2*(i+1)][2*(i+1)];
}
arr[0][0][0] = 0; //compiles


I would suggest think from the logic perspective rather than work around.

You are trying to use multidimensional arrays , your looping is in a single dimension{which might be right as per your requirements}. Can you post the pseudo code, this might help

This also works

public class NodeTest {
    public static void main(String[] args) {
        Object[] arr = new Object[5]; // each element of object will be an array
                                        // of integers.
        for (int i = 0; i < 5; i++) {
            int[][] a = new int[2 * (i + 1)][2 * (i + 1)];
            arr[i] = a;
        }
        arr[0] = 0; // Make it one dimensional
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消