有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从(整数列表)列表中删除元素时发生Java错误

删除(整数列表)中的一个元素时出错。 我使用迭代器删除该元素

这是我的代码:

List<List<Integer>> list = new ArrayList<List<Integer>>();
....
....
Iterator<List<Integer>> myListIterator = list.iterator();
int ct1 = 0;
while (myListIterator.hasNext()) {
    List<Integer> val = myListIterator.next(); // here is the error 
    if(ct1 == val.get(0))
        list.remove(val);
    ct1++;
}

我收到了这个错误信息:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
    at java.util.ArrayList$Itr.next(Unknown Source)

有人知道我的代码出了什么问题吗? 谢谢你们


共 (1) 个答案

  1. # 1 楼答案

    因为您在使用迭代器时删除了一个元素。一种可能的解决方案是,使用带有索引的循环,这样就可以安全地删除该元素。也可以使用myListIterator删除。移除()