简体   繁体   中英

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM