-4

これは、アイテムを削除する場所です。

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)

これは初めてのことなので、何が原因なのか想像できません.. :(

4

2 に答える 2

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


        }
    }
于 2013-10-21T12:32:55.647 に答える
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);
    }
}
于 2013-10-21T12:33:55.237 に答える