0

目前我创建了一个二维数组来表示迷宫的网格。我的迷宫构造函数如下:

public Maze(int rows, int columns)
{
    this.rows = rows;
    this.cols = columns;
    curr = new Square[rows][columns];
}

在我的测试课中有以下内容:

Maze m = new Maze(4, 4);

但是,当我遍历我的迷宫时,在调试时我注意到 curr 被初始化为 Square[4][] 没有列的参数。有谁知道这里可能出现什么问题?

编辑:这就是我打算做的;我使 curr = Square[rows][columns] 但是当我在以下循环中检查 curr 的值时,在调试器工具中,无论何时进入 curr[i][j ] 在循环中。

    for(int i = 0; i < maze.length; i++)
    {
        for(int j = 0; j < maze[i].length; j++)
        {
            /* Entrance */
            if(maze[i][j] == start)
            {
                startX = j;
                startY = i;
                curr[i][j] = new Square(i, j, start, this);
            }
            /* Exit */
            else if(maze[i][j] == end)
            {
                endX = j;
                endY = i;
                curr[i][j] = new Square(i, j, end, this);
            }
            /* Traversable Squares */
            else if(maze[i][j] == traverse)
            {
                curr[i][j] = new Square(i, j, traverse, this);
            }
            /* Non-traversable Squares */
            else
            {
                curr[i][j] = new Square(i, j, noTraverse, this);
            }
        }
    }
4

2 回答 2

1

enter image description here

Is this what you're seeing? In this case, the debugger only knows that curr is an array of Square arrays, not how many elements are in the sub-arrays. new Square[4][4] is a short-cut that automatically creates the inner array. Another way to do it would be:

Square[][] curr = new Square[4][];

for (int ctrOut = 0; ctrOut < 4; ctrOut++) {
    curr[ctrOut] = new Square[5];

    for (int ctrIn = 0; ctrIn < 5; ctrIn++) {
        curr[ctrOut][ctrIn] = new Square();
    }
}

So what the debugger is telling you appears to be correct. (Note, I used 4x5 for clarity, instead of 4x4.)

于 2012-09-10T22:26:22.923 回答
1

Java 使用“参差不齐的数组”作为多维数组。换句话说,即使您指定了一个矩形数组——所有行都具有相同的长度,java 允许行可能具有不同长度的可能性。

结果, curr = new Square[r][c] 创建了 r+1 个对象:

1 array with length r, where each element is an array of Squares (Square[])

r arrays of Squares, each of length c (although c could be changed for any of them)

所以curr实际上是一个Square[r][]:它是一个可变长度方数组的 r 元素数组,每个数组的长度恰好是 c 个元素。

curr[n]应该是一个Square[]curr[n][m]而是一个Square

于 2012-09-10T22:07:26.240 回答