簡體   English   中英

使用嵌套列表時的IndexOutOfBoundsException

[英]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范圍為09

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM