我创建了一个二维数组(一个Cell[][]
网格),每个单元格都包含一个ArrayList
名为neighborCells
; 现在我正试图找到它的相邻单元格,但我得到了IndexOutOfBoundsException
. 你能帮我吗?
ArrayList<Cell> neighborCells = new ArrayList();
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid.length; j++) { //we can also use grid.length since it is the same
int startPositionX = (i - 1 < 0) ? i : i - 1;
int startPositionY = (j - 1 < 0) ? j : j - 1;
int endPositionX = (i + 1 > grid.length) ? i : i + 1;
int endPositionY = (j + 1 > grid.length) ? j : j + 1;
for (int row = startPositionX; row <= endPositionX; row++) {
for (int col = startPositionY; col <= endPositionY; col++) {
neighborCells.add(grid[row][col]); // here is the error
}
}
}
}