繁体   English   中英

从ArrayList中移除时是否出现java.lang.IndexOutOfBoundsException?

[英]java.lang.IndexOutOfBoundsException while removing from ArrayList?

我正在尝试从ArrayList中删除对象,我的代码是

ArrayList myArrayList=new ArrayList();

for(int index=0;index<20;index++){
    myArrayList.add(index);
}

for(int removeIndex=0;removeIndex<=mArrayList;removeIndex++){
        myArrayList.remove(removeIndex);
}

它给出了java.lang.IndexOutOfBoundsException 如何从ArrayList删除多个对象?

当然,删除第0个项目后,最后一个项目现在为第18个,因为这些项目已重新索引。

您可以使用多种技巧,例如,从头开始删除。 或删除第0个项目,直到数组为空(或直到删除了一些预定义数量的项目)。

码:

for(int index = mArrayList.size() - 1; removeIndex >= 0; removeIndex--) {
    myArrayList.remove(removeIndex);
}

要么

for(int nremoved = mArrayList.size() - 1; nremoved >= 0; nremoved--) {
    myArrayList.remove(0);
}

如果要删除所有项目,也可以考虑使用clear()

如果要从列表中删除多个职位,可以尝试以下操作:

Collections.sort(positions); // needed if not already sorted
for (int i = positions.size() - 1; i >= 0; i--)
    myArrayList.remove(positions.get(i));

List#clear()将删除所有元素。

您正在将removeIndexArrayList本身进行比较,而不是与ArrayList.size() 另外,在比较中,应使用小于( < )而不是小于或等于( <= ),因为使用<会导致额外的循环,从而导致indexOutOfBoundsException

此外,请从ArrayList的末尾而不是在开头开始删除,以避免重新索引元素,这也可能导致indexOutOfBoundsException (在这种情况下不是这样,因为您要在每个循环中都与Array.size()进行比较。相反,您要删除每第二个项目,正如Vlad也提到的那样。)

删除时必须选中“ <”。

ArrayList myArrayList = new ArrayList();

        for(int index=0;index<20;index++){
            myArrayList.add(index);
        }

        for(int removeIndex=0;removeIndex<myArrayList.size();removeIndex++){
                myArrayList.remove(removeIndex);
        }

当您从ArrayList删除一个元素时,所有其后的元素会将其索引减小一。

请参考public ArrayList.remove(int index)

如果您需要从Array中删除所有元素,并且有可能的话,最好是

myArrayList = new ArrayList();

在内部循环中,您必须以这种方式重置Array,因为clear()removeAll()无效

通常,使用Iterator代替:

final Iterator<? extends T> it = collection.iterator();
while ( it.hasNext() ) {
    T t = it.next();
    if (isNeedToRemove(t)) {
        it.remove();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM