我不明白为什么我得到错误IndexOutOfBoundsException。代码wortks罚款2个删除器,但当我尝试添加第三个compilier甚至不开始。
public class Solution
{
public static void main(String[] args) throws Exception
{
// 1. Here im making list
ArrayList list = new ArrayList();
//2. Putting values: «101», «102», «103», «104», «105».
list.add( 101); //0
list.add( 102);
list.add( 103); //2
list.add( 104);
list.add( 105); //4
// 3. removing first, middle and the last one. here is main problem, i cant add list.remove(4)
list.remove(0);
list.remove(2);
list.remove(4);
// 4. Using loop to get values on screen
for ( int i = 0; i < list.size(); i++){
System.out.println(list.get(i));
}
// 5. here im printing out size of arr
System.out.println(list.size());
}
}
答案 0 :(得分:1)
删除arraylist的元素时,将移动以下所有元素。
列出内容:101,102,103,104,105
调用删除(0)
列表内容:102,103,104,105
调用删除(2)
列表内容:102,103,105
呼叫删除(4)
例外!没有索引4了。
从最高索引开始,以便正常工作:
list.remove(4);
list.remove(2);
list.remove(0);
...或选择其他方式删除元素。
答案 1 :(得分:0)
查看ArrayList的源代码。 remove
方法正在调用rangeCheck
方法,如果您尝试删除索引高于实际大小的元素,则会抛出IndexOutOfBoundsException
。