为什么我得到java.util.ConcurrentModificationException? [英] Why am I getting java.util.ConcurrentModificationException?

查看:180
本文介绍了为什么我得到java.util.ConcurrentModificationException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行以下代码:

    import java.util.LinkedList;

    class Tester {
      public static void main(String args[]) {
        LinkedList<String> list = new LinkedList<String>();
        list.add(new String("suhail"));
        list.add(new String("gupta"));
        list.add(new String("ghazal"));
        list.add(new String("poetry"));
        list.add(new String("music"));
        list.add(new String("art"));

        try {
            for(String s : list) {
            list.add(0,"art");
            list.remove(6);
            System.out.println(list);
        }
        }catch(Exception exc) {
            exc.printStackTrace();
        }

    }
}

我得到一个例外说:

java.util.ConcurrentModificationException
    at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
    at java.util.LinkedList$ListItr.next(Unknown Source)
    at Tester.main(Tester.java:14)

为什么我得到这个例外?

Why am I getting this exception ?

编辑:tmpList是一个LinkedList,其每个节点包含类型为DepConfAttr的对象。我正在基于内存排序tmpList(最高内存第一),这是DepConfAttr对象的属性之一。

上面的代码反映了我通过以下代码实现的目标:

The above code reflected what I am trying to achieve through the following code

int size = tmpList.size();
        int elementBC = 0; // element being checked
        int startIndex = 1;
        for (DepConfAttr dca : tmpList) {
            long maxMem = dca.getMemory(); // Let this be the maximum memory
            for(int i = startIndex ; i < size ; i++) {
                DepConfAttr dcaTmp = tmpList.get(i);
                if(maxMem < dcaTmp.getMemory()) {
                    tmpList.add(elementBC, dcaTmp);
                    tmpList.remove(i+1);
                    maxMem = tmpList.get(elementBC).getMemory();                        
                }
            }
            elementBC++;
            startIndex++;
            size--;
        }


推荐答案


为什么我得到这个例外?

Why am I getting this exception ?

您正在通过迭代器从列表中除去一个项目,同时迭代它。您还在添加列表,而您正在迭代。

You're removing an item from the list other than via the iterator, while iterating over it. You're also adding to the list while you're iterating over it.

这不是很清楚你在这里实现的是什么,但是除了并发集合,当您尝试执行此操作时,您总是会遇到异常。

It's not really clear what you're trying to achieve here, but other than with the concurrent collections, you'll always get an exception when you try to do that.

一个常见的修复方法是首先创建列表的副本,并重复一遍,修改原件。

One common fix to this is to create a copy of the list first and iterate over that, modifying the original as you go.

这篇关于为什么我得到java.util.ConcurrentModificationException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆