【问题标题】:arraylist remover doesnt work properly IOBEarraylist remover 无法正常工作 IOBE
【发布时间】:2014-02-08 22:21:01
【问题描述】:

我不明白为什么我收到错误 IndexOutOfBoundsException。使用 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());
    }
}

【问题讨论】:

    标签: java arrays arraylist int


    【解决方案1】:

    当你删除一个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);
    

    ...或选择其他方式删除元素。

    【讨论】:

    • 答案总是那么简单,但是当您寻找它时。现在我明白了。
    【解决方案2】:

    查看ArrayList的源码。 remove 方法正在调用 rangeCheck 方法,如果您尝试删除索引高于实际大小的元素,则会抛出 IndexOutOfBoundsException

    【讨论】:

    • 所以我必须输入类似 if(list.size()
    • 你真的不应该这样删除项目,而是使用list.remove(list.indexOf("105"));按值删除元素
    猜你喜欢
    • 2015-12-21
    • 2023-04-05
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2012-07-11
    • 2018-04-08
    相关资源
    最近更新 更多