Reputation: 119
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!
Upvotes: 0
Views: 57
Reputation: 209603
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; i.e. 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.
Upvotes: 5