简体   繁体   English

删除对象时ArrayList中的索引超出范围异常

[英]Index Out Of Bounds Exception in ArrayList while removing objects

Platform: JCreator 平台: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 线程“ AWT-EventQueue-0”中的异常java.lang.IndexOutOfBoundsException:索引:3,大小: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 . 尝试使用else if代替if

Otherwise one iteration in your loop may delete more than one element (once for the 'w' check and once for the 'h' check). 否则,循环中的一次迭代可能会删除多个元素(一次用于“ w”检查,一次用于“ h”检查)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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