简体   繁体   中英

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. However, I keep getting the IndexOutOfBoundsException when trying to put down a ship.

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);

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). So your Board() constructor doesn't add anything to theSea - the for loop is iterated zero times.

Consequently, theSea remains empty, and when you later call theSea.get(i) for any value of i , you get an 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; ie theSea.get(i) will return a list of size 0 for 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM