【问题标题】:having an error with arraylist in libgdxlibgdx 中的 arraylist 有错误
【发布时间】:2018-12-01 22:10:34
【问题描述】:
for (Rectangle block:getBlock()) {
for (Rectangle done:getDone()){

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

        dones.add(block);
        blocks.remove(block);
        create();

    }}

所以我试图为数组列表“块”和“完成”中的每个矩形获取位置 y,但我真的不知道当我运行这段代码时会发生什么,它就像它一样工作,直到 if (block.y == done.y + 40) 这实现了,我明白了例外:

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

附言在创建方法中,我将矩形添加到块数组列表中

【问题讨论】:

    标签: java android for-loop arraylist libgdx


    【解决方案1】:

    使用增强的 for 循环,您在内部使用 List 对象的迭代器。

    在迭代它时不允许修改底层列表。这称为ConcurrentModificationException,就是您现在所经历的。

    使用标准的 for 循环并确保在删除元素时正确移动索引以获得所需的功能,如下所示:

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

    【讨论】:

    • 我已经尝试过这样但我仍然得到Exception in thread "LWJGL Application" java.lang.ArrayIndexOutOfBoundsException: -1
    • 那不应该真的发生。你复制continue outer了吗?
    • 它成功了,谢谢,但你能告诉我那个外层是什么,以便我可以阅读它
    • 另外值得一提的是,使用带标签的循环通常被认为是“闻起来”。通常有更好的解决方案。对于这样一个简单的事情,我会认为它是一段工作代码:)
    猜你喜欢
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    • 2018-10-23
    • 1970-01-01
    相关资源
    最近更新 更多