Grinning Trout
Grinning Trout

Reputation: 119

having an error with arraylist in libgdx

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

Upvotes: 0

Views: 117

Answers (1)

Ben
Ben

Reputation: 1695

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
        }
    }
}

Upvotes: 2

Related Questions