[英]How to add custom made object to a 2D array of the same type
public static boolean[][] random(int[][] grid) {
boolean[][] a = new boolean[20][20];
for (int i = 0; i < grid1.length; i++) {
for (int j = 0; j < grid1.length; j++) {
Cell[] cellArray = null;
if (grid1[i][j] == 0) {
a[i][j] = false;
} else if (grid1[i][j] == 1) {
a[i][j] = false;
Cell cell = new Cell(i, j, 1);
} else if (grid1[i][j] == 3) {
a[i][j] = false;
Cell cell = new Cell(i, j, 3);
} else if (grid1[i][j] == 4) {
a[i][j] = true;
Cell cell = new Cell(i, j, 4);
} else if (grid1[i][j] == 5) {
a[i][j] = false;
}
}
}
return a;
}
我正在嘗試使用程序中它們的值將Cell對象添加到我的int網格中。 我在類中聲明了一個Cell[][] cellGrid = new Cell[20][20]
,我想將Cell對象添加到該網格中。 但是它應該與int[][] grid
。 有人可以幫忙嗎?
Cell[][] grid= new Cell[20][20];
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid.length;j++){
int temp= integer_array[i][j];
grid[i][j]= new Cell(temp);
//grid[i][j] will be an object of Cell class and any member of the class
//can be called
}
}
System.out.println(grid[0][1].data);
在您的問題中,您要求使用int[][] grid
作為元素。 在Java中,不可能執行運算符重載 。 所以'[]'不能專門針對從原始類型int
派生的單元元素定制。 您要求的功能只能在Java中通過定義一個類並使用類方法來尋址元素i,j
,即setElement(int x, int y, boolean value)
和getElement(int x, int y)
。 在C ++中,可以執行運算符重載。 但是,在某些情況下,這會導致代碼難以閱讀,因此Java中省略了此選項。
在Java中,也不能擴展基本類型int
以及自動裝箱的類Integer
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.