猿问

libgdx中的arraylist出现错误

for (Rectangle block:getBlock()) {

for (Rectangle done:getDone()){


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


        dones.add(block);

        blocks.remove(block);

        create();


    }}

所以我试图在arraylists“ blocks”和“ dones”中的每个矩形获取位置y,但是我真的不知道当我运行这段代码时会发生什么,直到它变为if (block.y == done.y + 40)现实,并且我得到了这个Exception:


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

ps在create方法中,将Rectangle添加到块arraylist中


繁华开满天机
浏览 125回答 1
1回答

明月笑刀无情

使用增强的for循环,您在内部使用List对象的迭代器。在迭代基础列表时,不允许对其进行修改。这就是ConcurrentModificationException您现在所经历的。使用标准的for循环,并确保在删除元素以获取所需功能时正确移动索引,如下所示:ArrayList<Rectangle> blocks = getBlock();ArrayList<Rectangle> done = getDone();outer: for(int i = 0; i < blocks.size(); ++i){&nbsp; &nbsp; for(int j = 0; j < done.size(); ++j)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if(blocks.get(i).y == done.get(j).y + 40)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; done.add(blocks.get(i));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; blocks.remove(i);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; --i; // Make sure you handle the change in index.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; create();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue outer; // Ugly solution, consider moving the logic of the inner for into an own method&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答