Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with ListIterator and Concurrent Modification Exception

I have two ArrayLists, each holding blocks of certain size: blockList, eraserList. Blocks are objects with two fields: start and end. I need to subtract one set of blocks from the other set of blocks.

I must walk through the eraserList and "erase" blocks out of the blockList where they overlap. Thus my code looks like:

 void eraseBlocks (Arrylist<Blocks> blockList, ArrayList<Blocks> eraserList) {
    ListIterator<Blocks> it = blockList.listIterator();

    for (Blocks eraser: eraserList) {
        while (it.hasNext()) {
            Blocks block= it.next();
            if ((eraser.start <= block.start) && (eraser.end >= block.end))
                 blockList.remove(block);
            else if ((eraser.start <= block.start) && (eraser.end < block.end)){
                 block.set(start, eraser.end);
            else if () {
                        ...
                 //more code for where the eraser partially erases the beginning, end, or splits the block
                 //if statements call the .add(), .set(), and remove() methods on the blockList.
                        ...
                  }
            }
        }

I don't understand why I am getting a Concurrent Modification Exception. I never modify the eraserList.

I am trying to modify the block object that is assigned in the "Block block = it.next();" statement. I am also modifying the blockList by removing or adding blocks to the list. I thought the whole point of the ListIterator was that it allowed you to modify, add, or subtract a list you are walking through.

The Failure Trace points to the Blocks eraser = it.next(); as the line drawing the exception, but I don't know what that is telling me.

Can anyone help me figure out what I am doing wrong?

Thanks!

like image 342
MyTimeFinder Avatar asked Feb 21 '23 08:02

MyTimeFinder


1 Answers

Yes, ListIterator is designed to allow the modification of the list. But you are not using the remove() method of the ListIterator, but directly manipulate the underlying list itself.

like image 118
Jan Avatar answered Apr 27 '23 18:04

Jan