![](/img/trans.png)
[英]IndexOutOfBoundsException when adding to ArrayList using nested while loops
[英]IndexOutOfBoundsException when using nested lists
我正在用Java构建基本的战舰风格游戏,并使用嵌套列表表示游戏网格。 但是,在尝试放下船只时,我一直收到IndexOutOfBoundsException。
游戏板具有如下构造函数
public Board(){
theSea = new ArrayList<ArrayList<ShipInterface>>(10);
for(int i = 0; i < theSea.size(); i++){
theSea.set(i, new ArrayList<ShipInterface>(10));
}
}
放置船只的方法如下:
public void placeShip(ShipInterface ship, Position position, boolean isVertical) throws InvalidPositionException, ShipOverlapException{
for(int i=0; i<ship.getSize(); i++){
theSea.get((position.getX()-1) + i).set(position.getY()-1, ship);
}
}
但是,我在theSea.get((position.getX()-1) + i).set(position.getY()-1, ship);
行中得到了错误theSea.get((position.getX()-1) + i).set(position.getY()-1, ship);
我是一个初学者,如果我缺少一些明显的代码,对不起!
创建新列表时,它的大小为0(传递给ArrayList
构造函数的值是初始容量 - 大小是当前包含的元素数)。 所以,你的Board()
构造函数不添加任何theSea -将for
循环迭代零次。
因此, theSea
仍然是空的,而当你再打theSea.get(i)
为任意值i
,你会得到一个ArrayIndexOutOfBoundsException
。
所以你可能打算做
public Board(){
theSea = new ArrayList<ArrayList<ShipInterface>>(10);
for(int i = 0; i < 10; i++){
theSea.add(new ArrayList<ShipInterface>(10));
}
}
现在注意, theSea
包含10个空列表; 即theSea.get(i)
将为0 <= i < 10
返回大小为0 <= i < 10
的列表。 因此,您的placeShip
方法将起作用,但placeShip
是每个列表中按顺序填充的y
范围为0
到9
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.