inconsistency between ArrayList.modCount and logic of ArrayList::addAll
Сергей Цыпанов
sergei.tsypanov at yandex.ru
Wed May 8 12:55:45 UTC 2019
Hello,
javadoc for AbstractList.modCount is described as
> The number of times this list has been <i>structurally modified</i>.
> Structural modifications are those that change the size of the
> list, or otherwise perturb it in such a fashion that iterations in
> progress may yield incorrect results.
However when we execute this
------------------------
ArrayList<Object> objects = new ArrayList<>();
boolean result = objects.addAll(Collections.emptyList());
------------------------
modCount is 1, not 0 while result is false. I.e. returned value claims the list is not modified, but the inner state of the same list demonstrates the opposite.
The reason is implementation of List::addAll method:
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
modCount++; // <------
int numNew = a.length;
if (numNew == 0)
return false; // <------
Object[] elementData;
final int s;
if (numNew > (elementData = this.elementData).length - (s = size))
elementData = grow(s + numNew);
System.arraycopy(a, 0, elementData, s, numNew);
size = s + numNew;
return true;
}
I think modCount++; should be placed after value of numNew is checked. Then it's incremented only when underlying array is actually changed.
Regards,
Sergei Tsypanov
More information about the core-libs-dev
mailing list