【问题标题】:ArrayList iterator remove crash [closed]ArrayList迭代器删除崩溃[关闭]
【发布时间】:2017-09-29 07:14:18
【问题描述】:

我在数组中有数组,我需要在第二个数组中找到一些项目并删除父数组,但是当我尝试删除数组时出现错误 java.lang.IllegalStateException

 productsList = new ArrayList<>(mSortModels);
    for (ProductComponentsResponse component : filterData) {
        String componentId = component.getId();
        int componentState = component.getState();
        Iterator<ProductResponse> iterator = productsList.iterator();
        while (iterator.hasNext()) {
            ProductResponse next = iterator.next();
            for (ProductComponentsResponse productComponentsResponse: next.getProductComponents()) {
                boolean containComponent = productComponentsResponse.getId().contains(componentId);
                if (componentState == ProductComponentsResponse.FilterState.NONE) {
                    continue;
                } else if (componentState == ProductComponentsResponse.FilterState.SELECTED) {
                    if (!containComponent) {
                        Log.d("component", String.valueOf(containComponent));
                        ***iterator.remove();*** - this error line
                    }
                } else if (componentState == ProductComponentsResponse.FilterState.UNSELECTED) {
                    if (containComponent) {
                        iterator.remove();

                    }
                }
            }
        }
    }
    notifyDataSetChanged();

【问题讨论】:

  • 您能更具体地说明错误吗?当时你的变量的状态是什么?你在哪一行得到错误? ..
  • 请将此信息添加到问题中,而不是在评论中

标签: java android


【解决方案1】:

Iterator.remove() 删除了父级,但您继续循环遍历子级。有时可能会再次在同一个父级上调用remove()。这可能会导致您的崩溃。

要解决这个问题:在两个 iterator.remove()s 之后放置一个 break;,以便在删除其父级后跳出内部 for 循环。这样您就不会继续循环已移除父级的子级。

【讨论】:

    【解决方案2】:

    我已经简化了你的代码 sn-p 使其更容易理解:

    ProductResponse next = iterator.next();
    for (ProductComponentsResponse productComponentsResponse: next.getProductComponents()) {
        if (condition1) {
            continue;
        } else if (condition2) {
            iterator.remove();
        } else if (condition3) {
            iterator.remove();
        }
    }
    

    您调用iterator.next() 一次,但随后进入for 循环,如果condition2condition3 满意,则删除迭代器。然后继续循环,如果对condition2condition3 满意,则再次删除在for 循环的上一步中删除的相同迭代器。所以你得到IllegalStateException。你应该只调用一次iterator.remove(),尝试在每个else if 块之后放置一个break;

    ProductResponse next = iterator.next();
    for (ProductComponentsResponse productComponentsResponse: next.getProductComponents()) {
        if (condition1) {
            continue;
        } else if (condition2) {
            iterator.remove();
            break;
        } else if (condition3) {
            iterator.remove();
            break;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-30
      • 1970-01-01
      • 2016-04-23
      • 2012-10-08
      • 1970-01-01
      • 2022-01-10
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      相关资源
      最近更新 更多