ArrayList 迭代器删除崩溃



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

Iterator.remove()删除了父项,但您继续循环遍历子项。有时可能会再次打电话给同一个父母remove()。这可能会导致您的崩溃。

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

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

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

最新更新