Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentModificationException after subList()

I'm running into this problem in a unit test.

After executing:

List<Card> cleanCards = cards.subList(0, cards.size() - difference);

the following assert gives me a ConcurrentModificationException:

assertEquals(limit, cleanCards.size());

Error description

java.util.ConcurrentModificationException 
at java.util.ArrayList$SubList.size(ArrayList.java:1057)

To my knowledge, the 'size()' method does not make structural changes to the list. Am I missing something here?

like image 850
ivopintodasilva Avatar asked Dec 09 '25 17:12

ivopintodasilva


1 Answers

Most likely the original list is being modified between the sub-list creation and its use. subList does not create an independent new list, but rather a view of a section of the original list, and as the specs say

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. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)

and in your case, the "undefined" behaviour seems to result in an exception being thrown, also known as fail-fast behaviour. I reckon an easy solution would be to change the first line above to

List<Card> cleanCards = new ArrayList<>(cards.subList(0, cards.size() - difference));

which copies the sub-list to a completely new list independent of the original.

like image 129
Leo Aso Avatar answered Dec 11 '25 05:12

Leo Aso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!