[英]IndexOutOfBoundsException when using nested lists
I'm building a basic battleship-style game in Java and am using nested lists to represent a game grid. 我正在用Java构建基本的战舰风格游戏,并使用嵌套列表表示游戏网格。 However, I keep getting the IndexOutOfBoundsException when trying to put down a ship. 但是,在尝试放下船只时,我一直收到IndexOutOfBoundsException。
The game board has the constructor as follows 游戏板具有如下构造函数
public Board(){
theSea = new ArrayList<ArrayList<ShipInterface>>(10);
for(int i = 0; i < theSea.size(); i++){
theSea.set(i, new ArrayList<ShipInterface>(10));
}
}
The method for placing the ship is as follows: 放置船只的方法如下:
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);
}
}
However, I get the error at the line 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);
I'm a beginner so sorry if I'm missing some obvious bit of code! 我是一个初学者,如果我缺少一些明显的代码,对不起!
When you create a new list, it has size 0 (the value you pass to the ArrayList
constructor is the initial capacity - the size is the number of elements it currently contains). 创建新列表时,它的大小为0(传递给ArrayList
构造函数的值是初始容量 - 大小是当前包含的元素数)。 So your Board()
constructor doesn't add anything to theSea - the for
loop is iterated zero times. 所以,你的Board()
构造函数不添加任何theSea -将for
循环迭代零次。
Consequently, theSea
remains empty, and when you later call theSea.get(i)
for any value of i
, you get an ArrayIndexOutOfBoundsException
. 因此, theSea
仍然是空的,而当你再打theSea.get(i)
为任意值i
,你会得到一个ArrayIndexOutOfBoundsException
。
So you probably intend to do 所以你可能打算做
public Board(){
theSea = new ArrayList<ArrayList<ShipInterface>>(10);
for(int i = 0; i < 10; i++){
theSea.add(new ArrayList<ShipInterface>(10));
}
}
Note now that theSea
contains 10 empty lists; 现在注意, theSea
包含10个空列表; ie theSea.get(i)
will return a list of size 0 for 0 <= i < 10
. 即theSea.get(i)
将为0 <= i < 10
返回大小为0 <= i < 10
的列表。 Thus your placeShip
method will work, but only as long as each list is populated with y
ranging from 0
to 9
, in order. 因此,您的placeShip
方法将起作用,但placeShip
是每个列表中按顺序填充的y
范围为0
到9
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.