有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ArrayList迭代器删除崩溃

我在数组中有数组,我需要在第二个数组中找到一些项并删除父数组,但当我尝试删除数组时,我遇到了一个错误。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();

共 (2) 个答案

  1. # 1 楼答案

    我简化了您的代码片段,使其更易于理解:

    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;
        }
    }
    
  2. # 2 楼答案

    Iterator.remove()删除了父项,但您继续在子项上循环。有时可能会再次对同一个父对象调用remove()。那可能会导致你坠机

    要解决这个问题:在两个iterator.remove()后面都放一个break;,当你移除了它的父循环时,它会跳出内部for循环。这样,您就不会继续循环删除父对象的子对象