I do not like this question because it implies knowledge of the implementation of ArrayList .
If we assume that the passed Object not null, you will have to reason with the code. Here is the inscription
public boolean add(E e) { ensureCapacityInternal(size + 1);
So how can this happen? Imagine that the size field is successfully growing, but the assignment of elementData is not yet available to the read stream.
In this case, the iterator will size contain the number of elements and can return zero (as it has not finished writing).
These are essentially two steps.
- Increment size
- Write elementData [size] = e
(1) can succeed while (2) is still in flight.
source share