![](/img/trans.png)
[英]How do I pass in populated list as a parameter in an object constructor?
[英]How do I pass an array parameter to an object from a constructor?
我需要從我制作的類中傳遞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;
}
我需要在主類中調用String maze[][]
,但我唯一知道的方法是將其稱為null。 我可以通過將其作為對象進行初始化的方式是什么? 我的null示例如下。
static Maze maze = new Maze(null,0,0,0,0);
有沒有一種方法可以調用String[][]
而不是僅調用null? 似乎是一個簡單的問題,但我找不到答案。
讓Maze
構造函數構建數組,刪除array參數並使用收到的行/列值:
public Maze(int xRows, int xColumns, int xxStart, int xyStart) {
maze = new String[xRows][xColumns];
rows = xRows;
columns = xColumns;
xStart = xxStart;
yStart = xyStart;
}
您不需要在構造函數中輸入數組和數組大小。
您可以創建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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.