Reputation: 31830
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 workaround 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
}
}
Upvotes: 1
Views: 26268
Reputation: 55223
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
Upvotes: 4
Reputation: 3499
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
}
}
Upvotes: 0
Reputation: 3576
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;
Upvotes: 7