I created a 2D array (a Cell[][]
grid) and each cell contains an ArrayList
with the name neighborCells
; and now I am trying to find its neighbour cells but I am getting the IndexOutOfBoundsException
. Can you help?
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
}
}
}
}