Bug in ArrayList iterator
Martin Buchholz
martinrb at google.com
Thu Jan 8 08:36:13 UTC 2015
I would not like to add to the overhead of ArrayList's iterator.
Those writing performance-critical code are avoiding the iterator and doing
for (int i = 0, limit = list.size(); i < limit; i++) {
E elt = list.get(i);
...
}
On Thu, Jan 8, 2015 at 12:11 AM, Remi Forax <forax at univ-mlv.fr> wrote:
>
> On 01/08/2015 03:24 AM, David Holmes wrote:
>
>> On 7/01/2015 7:45 PM, Remi Forax 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);
>>> }
>>>
>>> :(
>>>
>>> Rémi
>>> tip: the bug lies in ArrayList.Itr.hasNext() (and
>>> AbstractList.Itr.hasNext()).
>>>
>>
>> This is not a bug. The only supported way to remove from a collection you
>> are iterating over is to use an Iterator's remove method.
>>
>> http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#remove--
>>
>> "The behavior of an iterator is unspecified if the underlying collection
>> is modified while the iteration is in progress in any way other than by
>> calling this method."
>>
>> and as already pointed out the forEach docs make it clear you can't use
>> forEach in such a context as the Iterator is not exposed to you.
>>
>> So don't do that.
>>
>
> Hi David,
> while I agree that fail-fast behavior should be done on the best effort
> basis,
> i think like Paul said that the size should be stored in a field of the
> iterator because
> i don't see the point to try to support the fact that the size of the
> collection
> can change during the iteration.
>
> so in my opinion, it's not a bug but the current implementation of
> ArrayList.Itr should be changed
> or maybe there is a case where supporting a size changed is valid ?
>
>
>> David
>>
>>
>>
>>
> Rémi
>
>
More information about the core-libs-dev
mailing list