Unclear java.util.ConcurrentModificationException

Why did this happen?

I wrote this code and it throws java.util.ConcurrentModificationException

List<Integer> list = Stream.iterate(0, t -> t + 1).limit(10).collect(Collectors.toList());
System.out.println(list);
List<Integer> subList = list.subList(5, list.size());
list.removeAll(subList);
System.out.println(subList);
System.out.println(list);

But the following code does not throw

List<Integer> list = Stream.iterate(0, t -> t + 1).limit(10).collect(Collectors.toList());
System.out.println(list);
List<Integer> subList = list.subList(5, list.size());
System.out.println(subList);
list.removeAll(subList);
System.out.println(list);
+4
source share
2 answers

Looking at the Javadoc for the method subList(), it clearly states:

The semantics of the list returned by this method becomes undefined if the support list (i.e. this list) is structurally modified in any way except through the returned list.

In your first example, this is exactly what is happening: you are structurally modifying the support list by calling removeAll(), so the behavior of your sub-list is now not specified.

, ConcurrentModificationException, - .

, , ..

List<Integer> subList = new ArrayList<>(list.subList(5, list.size()));
list.removeAll(subList);

.

+4

, .

    List<Integer> subList = new ArrayList<>(list.subList(5, list.size()));
0

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


All Articles