Nathan Chan
Nathan Chan

Reputation: 177

Index Out Of Bounds Exception in ArrayList while removing objects

Platform: JCreator

I usually use for loops that count from the back because theoretically when removing they should collapse fine:

0123456789

removing even numbers:

i = 9: 0123456789
i = 8 //remove 8: 012345679
i = 7: 012345679
i = 6 //remove 6: 01234579

and so on

But I get this exception when the object is removed:

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3

for (int i = dArea.size() - 1; i >= 0; i--) {
    if (dArea.get(i).getOwn() == 1) {
        if (dArea.get(i).getSK() == 2) {
            if (dArea.get(i).getX() - dArea.get(i).getW() / 2 > 1350) {
                dArea.remove(i);
            }
            if (dArea.get(i).getX() + dArea.get(i).getW() / 2 < 0) {
                dArea.remove(i);
            }
            if (dArea.get(i).getY() - dArea.get(i).getH() / 2 > 685) {
                dArea.remove(i);
            }
            if (dArea.get(i).getY() + dArea.get(i).getH() / 2 < 0) {
                dArea.remove(i);
            }
        }
    }
}

Any ideas why and how to fix?

Upvotes: 0

Views: 1899

Answers (1)

Martin Ellis
Martin Ellis

Reputation: 9651

Try using else if instead of if.

Otherwise one iteration in your loop may delete more than one element (once for the 'w' check and once for the 'h' check).

Upvotes: 3

Related Questions