0
for (Rectangle block:getBlock()) {
for (Rectangle done:getDone()){

    if (block.y == done.y + 40) {

        dones.add(block);
        blocks.remove(block);
        create();

    }}

so im trying to get position y for every rectangle in the arraylists "blocks" and "dones" but i really dont know what happening when i run this code its like it works until if (block.y == done.y + 40) this comes true and i got this Exception :

Exception in thread "LWJGL Application" java.util.ConcurrentModificationException

p.s. in the create method im adding Rectangle to blocks arraylist

Grinning Trout
  • 109
  • 2
  • 13

1 Answers1

2

Using the enhanced for-loop you are internally using the iterator of your List objects.

It is not allowed to modify the underlying list while iterating over it. This is called a ConcurrentModificationException, what you are experiencing right now.

Use a standard for-loop and make sure you shift your index correctly when removing an element to get your desired functionality, something like this:

ArrayList<Rectangle> blocks = getBlock();
ArrayList<Rectangle> done = getDone();

outer: for(int i = 0; i < blocks.size(); ++i)
{
    for(int j = 0; j < done.size(); ++j)
    {
        if(blocks.get(i).y == done.get(j).y + 40)
        {
            done.add(blocks.get(i));
            blocks.remove(i);
            --i; // Make sure you handle the change in index.
            create();
            continue outer; // Ugly solution, consider moving the logic of the inner for into an own method
        }
    }
}
Ben
  • 1,665
  • 1
  • 11
  • 22
  • i have try to make it like this but i still got `Exception in thread "LWJGL Application" java.lang.ArrayIndexOutOfBoundsException: -1` – Grinning Trout Jun 22 '18 at 12:29
  • That should not really happen. Did you copy the `continue outer`? – Ben Jun 22 '18 at 12:32
  • it worked thank you but can you tell me what is that outer so i can read about it – Grinning Trout Jun 22 '18 at 12:37
  • Refer to this: https://stackoverflow.com/questions/3821827/loop-in-java-code-what-is-this-why-does-it-compile – Ben Jun 22 '18 at 12:38
  • Also it's important to mention that it's often considered to "smell" to use a labelled loop. More often than not there is a better solution out there. For such a simple thing as this here I would consider it a working piece of code though :) – Ben Jun 22 '18 at 12:39