我试图从列表中删除项目,但我得到并发修改异常?

时间:2013-10-21 12:29:25

标签: java

这是我要删除项目的地方,

myhieararchy hierarchyforDisplay = null;

    try {

        hierarchyforDisplay = (myhieararchy)hieararchybefore.clone();

    } catch (CloneNotSupportedException e) {

        e.printStackTrace();

    }

    for (Project project : projectList) {

    for (Program program : hierarchyforDisplay.getPrograms()) {

        for (Project rootproject : program.getProject()) {

            if(project.getId() != rootproject.getProjectId()){

                program.getProject().remove(rootproject);
            }
        }
    }
    }


    return hierarchyforDisplay;

但我得到了这个

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.util.ConcurrentModificationException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

我无法想象什么是共鸣,因为这是我第一次得到这个...... :(

2 个答案:

答案 0 :(得分:1)

除非使用iterator.remove()方法,否则在迭代该集合时无法从集合中删除项目。要使用它,您需要将增强型for循环的隐式迭代器转换为显式迭代器

    for (Project rootproject : program.getProject()) { //<-- here the enhanced for loop iterates over the collection

        if(project.getId() != rootproject.getProjectId()){

            program.getProject().remove(rootproject); //<--- here you attempt to remove from that collection
        }
    }

转换为显式迭代器并使用.remove()方法

    Iterator<Project> it=program.getProject().iterator();

    while(it.hasNext()){
        Project rootproject=it.next();

        if(project.getId() != rootproject.getProjectId()){

            it.remove(); //<--- iterator safe remove
            // iterator remove removes whatever .next() returned from the backing array (be aware; is implimented for most BUT NOT ALL collections, additionally for some collections creating a new collection can be more efficient


        }
    }

答案 1 :(得分:0)

for (Project rootproject : program.getProject()) {

        if(project.getId() != rootproject.getProjectId()){

            program.getProject().remove(rootproject);
        }
}

在上面的代码中,您在使用 for 循环进行迭代时对集合调用 remove()方法。它导致 ConcurrentModificationException 。使用 for循环进行迭代时,不能执行任何结构更改。

如果要在迭代时进行任何结构更改,请使用Iterator。

Iterator<Project> itr = program.getProject().iterator();
while(itr.hasNext()){
    Project rootProject = itr.next();

    if(project.getId() != rootproject.getProjectId()){

        itr.remove(rootproject);
    }
}