java 表达式的类型必须是数组类型,但解析为Object
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7369503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The type of an expression must be an array type, but it is resolved to Object
提问by Anderson Green
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
}
}
}
回答by Brett Walker
arr
is Object[]
so arr[0]
will return an Object
arr
是Object[]
这样arr[0]
会返回一个Object
But since you know that arr
contains int[][]
as instance of Object
you will have to cast them to be so.
但是既然你知道arr
包含int[][]
作为实例,Object
你就必须将它们转换成这样。
( ( int[][] ) arr[0] )[0][0] = 0;
回答by Paul Bellora
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.
您想声明arr
为 asint[][][]
而不是Object[]
。虽然阵列式Object
所以在循环分配是合法的,你再失去该类型的信息,以便编译器不知道的元素arr
都int[][]
在底线。
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
回答by Manish Singh
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
}
}