简体   繁体   English

如何修复ConcurrentModificationException,从arrayList中删除项目?

[英]How to fix ConcurrentModificationException, removing item from arrayList?

I would like to delete an item from my arrayList while iterating through it, and the ArrayList has a type class Members. 我想在遍历它时从我的arrayList中删除一个项目,并且ArrayList具有类型类Member。 I have read multiple examples of how to fix this problem however none have worked, the ConcurrentModificationException is still thrown. 我已经阅读了多个如何解决此问题的示例,但是都没有成功,仍然抛出ConcurrentModificationException

Iterator<Members> itr = members.iterator();
while (itr.hasNext()) {
  Members foundMember = itr.next();
  if (foundMember.equals(member)){
    itr.remove();
  }
}

The solution i ended up with was, using a CopyOnWriteArrayList, instead of an ArrayList nad using the remove(); 我最终得到的解决方案是使用CopyOnWriteArrayList,而不是使用remove()的ArrayList。 methode. 方法。

EDIT of course my first solution was incorrect facepalm as suggested above, ".removeIf" is most likely the simplest solution. 编辑当然,我的第一个解决方案是上面建议的不正确的facepalm ,“。removeIf”最有可能是最简单的解决方案。

just use a "normal" for loop (I think that should work, pls. take a look at this , btw. an "enhanced for loop" will not work. 只需使用一个“正常”的循环(我认为这应该工作,请。看看这个 ,顺便说一句。“增强的for循环”将无法正常工作。

List<Member> list1 = new ArrayList<>();
List<Member> list2 = new ArrayList<>(list1);
for (int i = 0; i < list1.size(); i++) {
  Member member = list1.get(i);
  ...
  list2.remove(member);
}
list1 = list2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM