【问题标题】:Why is out of bounds error thrown?为什么会抛出越界错误?
【发布时间】:2014-11-28 18:04:22
【问题描述】:

我有以下代码通过大小为 8 的 ArrayList

public Tile[] getTiles(){

    Tile[] tiles = {};

    for(int i = 0; i < board.size(); i++){

        try {
            tiles[i] = board.get(i);
        } catch(ArrayIndexOutOfBoundsException e){

            System.out.println(i + " is out of bounds");
        }

    }

    return tiles;
}

但是输出

 0 is out of bounds
 1 is out of bounds
 2 is out of bounds
 3 is out of bounds
 4 is out of bounds
 5 is out of bounds
 6 is out of bounds
 7 is out of bounds
 8 is out of bounds

为什么ArrayList 中的所有元素都超出范围?

【问题讨论】:

    标签: java arrays arraylist indexoutofboundsexception


    【解决方案1】:

    tiles 被初始化为一个空数组(长度为 0)。那是你的问题。 它使tiles[i] 超出任何i 的范围。

    您应该以这种方式初始化tiles,使其长度与board的大小相同:

    Tile[] tiles = new Tile[board.size()];
    

    【讨论】:

      【解决方案2】:

      这是由于空数组。

      Tile[] tiles = {};

      并且您正在尝试使用索引值访问空数组,例如1,2 .....等等。这就是为什么它显示出站。

      【讨论】:

        猜你喜欢
        • 2019-08-26
        • 2021-11-17
        • 1970-01-01
        • 1970-01-01
        • 2020-07-26
        • 2013-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多