Bug in ArrayList iterator

Daniel Fuchs daniel.fuchs at oracle.com
Wed Jan 7 10:47:56 UTC 2015


On 07/01/15 11:31, Paul Sandoz wrote:
>
> On Jan 7, 2015, at 10:45 AM, Remi Forax <forax at univ-mlv.fr> wrote:
>
>> A simple Java question, what this code does ?
>>
>>   ArrayList<String> list = new ArrayList<>();
>>   list.add("foo");
>>   list.add("bar");
>>   for(String s: list) {
>>     list.remove(s);
>>   }
>>
>> :(
>>
>
> We could improve the best-effort basis by which ConcurrentModificationException is thrown by snapshotting the collection size on construction of the iterator (at the expense of an extra field, but that might pack into a spare 4 bytes due to alignment at least on 64 bits IIUC).

Or call checkForComodification() when cursor == size in hasNext()?

-- daniel

>
> Paul.
>
>> Rémi
>> tip: the bug lies in ArrayList.Itr.hasNext() (and AbstractList.Itr.hasNext()).
>>
>




More information about the core-libs-dev mailing list