简体   繁体   中英

How to work around this ConcurrentModificationException

I'm trying to implement an algorithm to generate BSP trees within my application. The problem I'm having is that I need to loop through all of the "children" of each "parent", and split them and add those children to a list, and continue to iterate through the children.

I'm lost on how to do this with using concurrent modification.

public void generate() {
    Parent root = new Parent(0, 0, width, height);
    parents.add(root);

    boolean did_split = true;

    while (did_split) {
        did_split = false;
        for (Parent p : parents) {
            if (p.leftChild == null && p.rightChild == null) {
                if (p.width > MAX_SIZE || p.height > MAX_SIZE || Math.random() > 0.25) {
                    if (p.split()) {
                        parents.add(p.leftChild);
                        parents.add(p.rightChild);
                        did_split = true;
                    }
                }
            }
        }
    }   
}

parents is an ArrayList that is defined earlier within the class.

Since you've got an ArrayList , you can use its ListIterator . As you can't add a new value to something you're iterating over with a plain Iterator (which is what the enhanced-for is using under the hood), using the ListIterator will give you access to an add method.

You'll also have to do a bit more work to get it to insert things in the places you expect it to; namely, you have to move the cursor back one position so that iteration can continue (since you're bounded by whether or not you have an element in your iterator to continue iteration with.

for (ListIterator<Parent> iterator = parents.listIterator(); iterator.hasNext(); ) {
    Parent p = iterator.next();
    if (p.leftChild == null && p.rightChild == null) {
        if (p.width > MAX_SIZE || p.height > MAX_SIZE || Math.random() > 0.25) {
            if (p.split()) {
                parents.add(p.leftChild);
                iterator.previous();
                parents.add(p.rightChild);
                iterator.previous();
                did_split = true;
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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