Removing an item when reassembling

I am wondering what really happens behind the scenes when I execute the following code:

List<Object> list = new ArrayList<Object>(); fillTheList(); // Filling a list with 10 objects int count = 0; for (Object o : list) { count++; if (count == 5) { list.remove(count); } o.toString(); } 

As soon as the item is deleted, I get a ConcurrentModificationException .

I do not understand why, after deleting one of the elements, it is impossible to simply make the next available in the collection and continue the cycle.

+4
source share
3 answers

get an Iterator instead of using an iterator in a for loop:

 int count = 0; for(final Iterator iterator = list.iterator(); iterator.hasNext();) { final Object o = iterator.next(); if (++count == 5) { iterator.remove(); } o.toString(); } 

edit: the reason you get a ConcurrentModificationException is because the for loop uses another Iterator that was created before you make the modification with list.remove() , and that Iterator has an internal state.

+7
source

Basically, you are not allowed to reference the collection ( list in this case) inside the foreach loop.

Try this instead:

 List<Object> list = new ArrayList<Object>(); fillTheList(); // Filling a list with 10 objects int count = 0; ListIterator<Object> it = list.listIterator(); while (it.hasNext()) { Object o = it.next(); count++; if (count == 5) { it.remove(); } o.toString(); } 
+1
source

There is usually a better way to do this rather than using iterator.remove (). for example, in your case, the loop is the same as

 if(list.size()> 5) list.remove(5); 

If you need to use iterator.remove (), you can still use a for loop.

 for(Iterator iterator = list.iterator(); iterator.hasNext();) { final Object o = iterator.next(); if (++count == 5) iterator.remove(); o.toString(); } 
0
source

Source: https://habr.com/ru/post/1332881/


All Articles