【发布时间】:2017-08-04 10:37:46
【问题描述】:
这段代码是关于一个水罐车在一个环境中徘徊寻找有任务的水站。
尝试通过访问点的 ArrayList 递增,但每次运行代码时,我都会得到一个“IndexOutOfBoundsException”,但在不同的索引处,并且大小始终与索引相同,所以我很困惑。破坏程序的索引/大小似乎是随机变化的。
示例错误: 线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:5,大小:5
相关代码(假设无限运行):
int stationIncrementer = 0;
ArrayList<Point> stationList = new ArrayList<Point>();
ArrayList<Point> wellList = new ArrayList<Point>();
Iterator it = stationList.iterator();
public Action senseAndAct(Cell[][] view, long timestep) {
// Loop to scan every cell in view for stations
int i = 0, j = 0;
for (i = 0; i < 25; i++) {
for (j = 0; j < 25; j++) {
Cell c = view[i][j];
if (view[i][j] instanceof Station) {
Task t = ((Station) c).getTask();
Point p = view[i][j].getPoint();
if (stationList.contains(p)) {
break;
} else if (t != null) {
stationList.add(p);
}
}
if (j == 25) {
j = 0;
}
}
}
if (it.hasNext() && stationList.get(stationIncrementer) != null && getWaterLevel() > 0
&& !(getCurrentCell(view) instanceof Station)) {
Point p = stationList.get(stationIncrementer);
stationIncrementer++;
return new MoveTowardsAction(p);
}
【问题讨论】:
-
索引是从 0 开始的,例如大小 5 只有有效索引 0..4
-
你能看出索引随机超出范围的任何原因吗?正如我所说,错误发生在几个不同的值上
-
不,因为你没有显示view[][]的初始化代码
-
view 只是 Cell 的实例化,它只是一个 2D 数组
-
这段代码也不应该捕获 OutOfBoundsException 吗?: if (it.hasNext() && stationList.get(stationIncrementer) != null
标签: java arraylist indexoutofboundsexception