When deleting inside foreach we need to retreat

Take this Java code:

for (ContactsReduced curContact : allcontacts) { .......... allcontacts.remove(curContact); } 

I am based on the deletion condition, will skip skip the next element in order, and do we need to back off (somehow)?

+7
java foreach
source share
5 answers

This code will be broken down into most collections - except for a few collections, such as those found in java.util.concurrent , modifying the collection, while iterating over it is not supported.

Several variants:

  • Get and use the iterator explicitly (calling iterator() in the collection) instead of the extended loop of the loop and calling iterator.remove() to remove the element
  • Use a simple loop, moving forward and backing off after deleting or moving backward from the end.
  • Keep a separate list of items to delete, and then delete them after iteration
+8
source share

Take a look at the section on iterators in the collection interface tutorial

Use an Iterator instead of a for-each construct when you need to remove the current item. The for-each construct hides the iterator, so you cannot call remove. Therefore, it is not possible to use filtering for each design.

Note that Iterator.remove is the only safe way to modify a collection during iteration.

+3
source share
 List<Integer> al = new ArrayList<Integer>(); for(int i=0;i<10;i++){ al.add(i); } for(Integer x:al){ al.remove(x); System.out.println(al); } 

Well, the question is interesting, so I tried it on my system, and this is the wat I got.

 Exception in thread "main" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(Unknown Source) at java.util.AbstractList$Itr.next(Unknown Source) at test.Main.main(Main.java:17) 
+1
source share

He definitely advised against interfering with the collection upon repetition. I'm not sure Java even allows this; this may cause an exception. I know what C # does ...

0
source share

The iterator will not work with ConcurrentModificationException. The way the creation infrastructure is developed.

0
source share

All Articles