I have very simple code:
List<String> list = new ArrayList<String>();
String a = "a";
String b = "b";
String c = "c";
String d = "d";
list.add(a);
list.add(b);
list.add(c);
List<String> backedList = list.subList(0, 2);
list.add(0, d);
System.out.println("2b: " + backedList);
And I get ConcurrentModificationException exception by list.add(0, d). So in general, it’s because of sublist(). I’m very confused, because in case of sublist() the documentation says:
The returned list is backed by this list, so non-structural changes in
the returned list are reflected in this list, and vice-versa.
Could you explain me where the catch is?
The
subListis simple a view of the original list (see here). You are allowed to mutate elements within it but not change the structure of the list.According to the documentation,
subListbehaviour is undefined if you try to make structural changes. I guess in this particular implementation,ConcurrentModificationExceptionwas decided as the undefined behaviour.