There's this strange code in AbstractCollection
:
public Object[] toArray() {
// Estimate size of array; be prepared to see more or fewer elements
Object[] r = new Object[size()];
Iterator<E> it = iterator();
for (int i = 0; i < r.length; i++) {
if (! it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);
r[i] = it.next();
}
return it.hasNext() ? finishToArray(r, it) : r;
}
The part "be prepared to see more or fewer elements" is IMHO a pure non-sense:
- In case the collection changes in the meantime, the iterator throw a
ConcurrentModification
exception anyway. - I haven't found any non-concurrent subclass supporting this, especially
- the
ArrayList
usesArrays.copyOf(elementData, size)
which could (due to visibility issues) copy a bunch ofnull
s instead of the data in case of resizing, - the
LinkedList
throws anArrayIndexOutOfBoundsException
if you're lucky enough.
- the
Am I overlooking something?
Would you support this feature in your collection (meant for general use)?