使用嵌套列表时IndexOutOfBoundsException

Br*_*ian 0 java nested arraylist bluej

我正在用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));
    }
}
Run Code Online (Sandbox Code Playgroud)

放置船舶的方法如下:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到了错误 theSea.get((position.getX()-1) + i).set(position.getY()-1, ship);

我是初学者,如果我错过了一些明显的代码,我很抱歉!

Jam*_*s_D 5

创建新列表时,它的大小为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));
    }
}
Run Code Online (Sandbox Code Playgroud)

现在注意theSea包含10个空列表; ie theSea.get(i)将返回一个大小为0的列表0 <= i < 10.因此,您的placeShip方法将起作用,但只要每个列表按顺序填充y范围为0to 9.