【发布时间】:2014-07-27 08:02:12
【问题描述】:
我创建了一个二维数组(Cell[][] 网格),每个单元格都包含一个名为 neighborCells 的 ArrayList;现在我正试图找到它的邻居单元,但我得到了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
}
}
}
}
【问题讨论】:
-
ArrayList 是如何定义的?是 .NET 类还是 Java 类?
-
好的,很抱歉弄乱了你的答案。你又编辑了。我认为现在不正确。
neighborCells不是你想得到的邻居集合吗? -
是的,neighborCells 是包含网格邻居的 ArrayList。每个 grid[i][j] 都有一个它的邻居数组列表。
-
同时我快速(但错误!)的第一个答案被删除了。请检查您是否可以接受新的。我尝试了 C++ 中的代码,它完成了它应该做的事情。
-
它对我不起作用。我做了你在下面推荐的事情,我得到了错误 neighnorCells has private access in Cell(在你提出的第二个更改中。)
public class Cell里面有一个private ArrayList<Cell> neighborCells;。
标签: java arrays multidimensional-array indexoutofboundsexception neighbours