【问题标题】:removing integer from ArrayList IndexOutOfBoundsException [duplicate]从 ArrayList IndexOutOfBoundsException 中删除整数 [重复]
【发布时间】:2016-04-15 01:03:07
【问题描述】:
import java.util.Random;
import java.util.ArrayList;
public class Game {
ArrayList<Integer> numere = new ArrayList<>();
ArrayList<Bila> balls = new ArrayList<Bila>();
ArrayList<String> culori = new ArrayList<>();
Random random = new Random();
int nrBalls=0;
public void createColours(){
    for(int i=0;i<7;i++){
        culori.add("Portocaliu");
        culori.add("Rosu");
        culori.add("Albastru");
        culori.add("Verde");
        culori.add("Negru");
        culori.add("Galben");
        culori.add("Violet");
    }
}
public void createNumbers(){
    for(int i=1;i<50;i++){
        numere.add(i);
        System.out.print(numere.size());
    }
}
public void createBalls(){
    while(nrBalls<36){
        int nr =numere.get(random.nextInt(numere.size()));
        numere.remove(nr);
        String culoare =culori.get(random.nextInt(culori.size()-1));
        culori.remove(culoare);
        balls.add(new Bila(culoare,nr));
        nrBalls++;
    }
}
}

所以我有另一个带有 main 方法的类,在该类中我调用 createNumbers()、createColours()、createBalls()。当我运行程序时,我在 numere.remove(nr) 处得到一个 IndexOutOfBoundsException,说 index:a number和大小:另一个数字..总是第二个数字小于第一个数字..为什么会发生这种情况?我哪里错了?

【问题讨论】:

  • @Tunaki 这在我看来并不重复。 “第一个问题”是关于“导致 java.lang.ArrayIndexOutOfBoundsException 的原因以及如何防止它”,而这个问题是关于“当您尝试在整数列表上调用 remove 方法时,为什么有时会出现 ArrayIndexOutOfBoundsException”。是我,还是那个……他们不是重复的?

标签: java arraylist


【解决方案1】:

问题在于 ArrayList.remove() 有两种方法,一种是 Object,另一种是 (int index)。当您使用整数调用 .remove 时,它​​会调用 .remove(int) 来删除索引,而不是对象值。

作为对评论的回应,这里有更多信息。

int nr = numere.get(random.nextInt(numere.size()) 行返回调用返回的索引处对象的。下一行numere.remove(...) 尝试从 ArrayList 中删除该值。

您可以采用以下两种方式之一:

int idx = random.nextInt(numere.size());
int nr = numere.get(idx);
numere.remove(idx);

.remove(int)方法返回对象的remove值,你也可以这样做:

int idx = random.nextInt(numere.size());
int nr = numere.remove(idx);

当然,如果需要,您可以将这两行合并为一条。

【讨论】:

  • 是的,我希望它删除我的数组列表中那个位置的数字
  • @BaiRadule 提供了更新的答案,并提供了更多解释。本质上,原始代码从数组中获取 value,然后尝试从索引中删除 value 而不是索引位置。
  • 谢谢,这是我一直在寻找的答案
【解决方案2】:

numere -- ArrayList 只包含整数 1 到 49。

numere.remove(nr); -- 这里 nr 可以是整数范围内的任意数字。因为它是由随机函数创建的。所以它抛出一个错误。您只能删除数组列表中的元素。 else 程序会抛出异常

【讨论】:

    【解决方案3】:

    remove(int) 将删除给定索引处的元素,而不是等于给定值的元素。它还返回删除的元素,所以你可以简单地做:

    int nr = numere.remove(random.nextInt(numere.size()));
    

    你可以为你的 culoare 做同样的事情:

    String culoare = culori.remove(random.nextInt(culori.size()));
    

    请注意,如果参数为零(如果您的 List 为空),Random.nextInt(int) 将抛出异常。

    【讨论】:

    • 是的,但如果随机数是 ex 32,那么我的数组中数字 32 的索引将为 31,所以如果我输入 numere.size()-1 将删除我想要的确切数字。 .但它仍然给我同样的错误
    • 我的列表不会是空的,因为它只包含 35 个数字......而我的数组有 49 个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2018-05-29
    • 2014-08-28
    • 2014-03-25
    • 2015-12-12
    • 1970-01-01
    • 2020-03-06
    相关资源
    最近更新 更多