[英]arraylist remover doesnt work properly IOBE
我不明白为什么我收到错误IndexOutOfBoundsException。 代码wortks很好,带有2个卸妆器,但是当我尝试添加第三个卸妆器时,它甚至不会启动。
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());
}
}
当您删除arraylist的元素时,以下所有元素将被移动。
清单内容:101、102、103、104、105
调用remove(0)
清单内容:102、103、104、105
调用remove(2)
清单内容:102、103、105
调用remove(4)
例外! 不再有索引4。
从最高索引开始以正常工作:
list.remove(4);
list.remove(2);
list.remove(0);
...或选择其他删除元素的方法。
查看ArrayList的源代码。 remove
方法正在调用rangeCheck
方法,如果您尝试删除索引大于实际大小的元素,该方法将抛出IndexOutOfBoundsException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.