从ArrayList中删除整数IndexOutOfBoundsException

import java.util.Random; import java.util.ArrayList; public class Game { ArrayList numere = new ArrayList(); ArrayList balls = new ArrayList(); ArrayList 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索引)。 当您使用整数调用.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)方法返回删除对象的值,你也可以这样做:

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

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

numere – ArrayList只包含1到49个整数。

numere.remove(NR); – 这里nr可以是整数范围内的任何数字。 因为它是由随机函数创建的。 所以这是一个错误。 你只能删除arraylist中的元素。 else程序会抛出exception

remove(int)将删除给定索引处的元素,而不是等于给定值的元素。 并且它还返回已删除的元素,因此您可以简单地执行:

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

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

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

请记住,如果参数为零(如果列表为空), Random.nextInt(int)将抛出exception。