java - 从 ArrayList 中删除整数 IndexOutOfBoundsException

标签 java arraylist

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 ,说索引:一个数字和大小:另一个数字..第二个数字总是小于第一个数字..为什么会发生这种情况?我错在哪里?

最佳答案

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

为了回复评论,这里有更多信息。

int nr = numbere.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);

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

关于java - 从 ArrayList 中删除整数 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36628963/

相关文章:

java - 在Java中创建具有唯一id的列表并对其进行操作

java - Vector 与 ArrayList 同步的示例

Java,程序最后只做了repaint()

java - Solr查询sdouble字段不为空

java - 如何从主类调用静态方法?

java - 如何在没有逗号和括号的情况下将列表转换为字符串

Java IntelliJ 13.1.4 "Lambda expressions are not supported at this language level."

java - 使用 WSDL 从客户端发送到 Web 服务的对象在 Web 服务上为 null,但在客户端中却不是,为什么?

java - 从ArrayList中删除学生ID,并显示添加到ArrayList中的所有类(class)

java - 将 ArrayList<> 转换为 TableView 的 ObservableList<>