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/