从ArrayList中删除整数IndexOutOfBoundsException [英] removing integer from ArrayList IndexOutOfBoundsException

查看:136
本文介绍了从ArrayList中删除整数IndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:一个数字和大小:另一个数字..总是第二个数字小于第一个数字..为什么会这样?我在哪里错了?

So i have another class with main method and in that class i call createNumbers() ,createColours(),createBalls().when i run the program i get an IndexOutOfBoundsException at numere.remove(nr) saying index:a number and size:another number ..always the second number is smaller than the first number..Why is this happening ?where am I wrong?

推荐答案

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

The problem is that ArrayList.remove() has two methods, one that is an Object, and one that is an (int index). When you call the .remove with an integer, it is calling the .remove(int) which removes the index, not the object value.

在回应评论时,这里有更多信息.

In response to a comment, here is a bit more information.

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

The line int nr = numere.get(random.nextInt(numere.size()) returns the value of the object at the index returned by the call. The next line numere.remove(...) attempts to remove from the ArrayList the value.

您可以执行以下两种方法之一:

You can do one of two ways:

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

.remove(int)方法返回对象的remove的值,您也可以执行以下操作:

The .remove(int) method returns the value of the remove of object, you can also do:

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

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

Of course, you can consolidate those two lines into a single one if desired.

这篇关于从ArrayList中删除整数IndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆