0

I would like to delete an item from my arrayList while iterating through it, and the ArrayList has a type class Members. I have read multiple examples of how to fix this problem however none have worked, the ConcurrentModificationException is still thrown.

Iterator<Members> itr = members.iterator();
while (itr.hasNext()) {
  Members foundMember = itr.next();
  if (foundMember.equals(member)){
    itr.remove();
  }
}
Vikas
  • 6,868
  • 4
  • 27
  • 41

2 Answers2

0

The solution i ended up with was, using a CopyOnWriteArrayList, instead of an ArrayList nad using the remove(); methode.

-1

EDIT of course my first solution was incorrect facepalm as suggested above, ".removeIf" is most likely the simplest solution.

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.

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;
JavaMan
  • 1,142
  • 12
  • 22