如何将数组参数从构造函数传递给对象?

How do I pass an array parameter to an object from a constructor?

我需要从我制作的 class 传递一个 String[][] 参数,例如:

public class Maze {

    String maze[][];
    int rows;
    int columns;
    int xStart;
    int yStart;

    public Maze(String xMaze[][], int xRows, int xColumns, int xxStart, int xyStart) {     
        maze = xMaze;
        rows = xRows;
        columns = xColumns;
        xStart = xxStart;
        yStart = xyStart;
    }

我需要在主 class 中调用 String maze[][],但我知道这样做的唯一方法是将其称为 null。我可以通过将其作为对象调用来初始化它的方法是什么?下面是我的 null 示例。

static Maze maze = new Maze(null,0,0,0,0);

有没有办法调用 String[][] 而不仅仅是空值?看似很简单的问题,我却找不到答案。

您可以创建 String 数组的实例并传递它

String[][] ar = new String[2][3]; // initialize with appropriate size
Maze maze = new Maze(ar,0,0,0,0);
Maze maze = new Maze(new String[2][2],0,0,0,0);

Maze 构造函数构建数组,删除数组参数并使用收到的 row/column 值:

public Maze(int xRows, int xColumns, int xxStart, int xyStart) {     
    maze = new String[xRows][xColumns];
    rows = xRows;
    columns = xColumns;
    xStart = xxStart;
    yStart = xyStart;
}

您不需要在构造函数中输入数组和数组大小。