-2

I have an arrayList of complex objects Box. I need a specific element of these Boxes to be moved to the last position of the arrayList and have the original one removed like shown in the diagram:

enter image description here

My code is something like this, but I get this error: ConcurrentModificationException

for (Box i : boxes) {  //where boxes is the arrayList
 if (i.mouseOver()) {  //does the swapping I need if the mouse is over the box
  
  Box copy=i;
  boxes.remove(i);  //these 3 lines are where I think the mistake is
  boxes.add(copy);
 }
}
  • 1
    The problem seems to be that you are trying to modify a `Collection` on which you are iterating. You have to create a new `Collection` and modify that. – Tanbir Ahmed Dec 07 '21 at 15:07
  • 1
    Does this answer your question? [How to avoid "ConcurrentModificationException" while removing elements from \`ArrayList\` while iterating it?](https://stackoverflow.com/questions/18448671/how-to-avoid-concurrentmodificationexception-while-removing-elements-from-arr) – Christopher Schneider Dec 07 '21 at 15:08
  • 1
    Never use a *for-each* loop to modify a Java list! I suggest you to look at [this request](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re), which explains your problem and their solutions – 0009laH Dec 07 '21 at 15:09

3 Answers3

1

Once you modify the boxes (by removing and or adding elements) you cannot continue iterating over it. One way you can avoid that would be by breaking out of the loop once you move the Box you want to move:

for (Box i : boxes) {  //where boxes is the arrayList
    if (i.mouseOver()) {  //does the swapping I need if the mouse is over the box
        // No need to create a new reference
        boxes.remove(i);
        boxes.add(i);
        break;
    }
}
John Bollinger
  • 160,171
  • 8
  • 81
  • 157
0

You cannot remove entries while in a for-each loop.

for (int i = 0; i < boxes.size(); i++) {
    if (boxes.get(i).mouseOver())
        boxes.add(boxes.remove(i));
}
0

If java.util.ConcurrentModificationException is the error you were getting, try not to use advanced for loop and just use regular for loop. Also in your code I see you are trying to remove the element from the list with the actual object. In Arraylist you can only remove by the index, not the element.

I think below should work.

for (int i = 0; i < boxes.size(); i++) {
    if (boxes.get(i).mouseOver()) { 
        boxes.add(boxes.remove(i));
    }
}