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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:42:00  来源:igfitidea点击:

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

javaarraysobject

提问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

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

arrObject[]这样arr[0]会返回一个Object

But since you know that arrcontains int[][]as instance of Objectyou will have to cast them to be so.

但是既然你知道arr包含int[][]作为实例,Object你就必须将它们转换成这样。

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

回答by Paul Bellora

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

您想声明arr为 asint[][][]而不是Object[]。虽然阵列式Object所以在循环分配是合法的,你再失去该类型的信息,以便编译器不知道的元素arrint[][]在底线。

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
    }
}