Skip to content
Advertisement

ConcurrentModificationException with map of lists

JavaScript

The code above is buggy in that it produces the wrong result; the “zeros” list is aliased everywhere (I think; I’m learning Java)

JavaScript

Test input

JavaScript

Exception thrown

JavaScript

Advertisement

Answer

The problem is a misconception around this line:

JavaScript

You’re not “fixing the aliasing bug”. The method subList does not return a new list. As 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.”

It then says: “The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list.”

You’re structurally modifying the list, since you add an element (zeros.add(0)) to the original list after creating the sublist.

You should create a new list instead:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement