1

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 uses Arrays.copyOf(elementData, size) which could (due to visibility issues) copy a bunch of nulls instead of the data in case of resizing,
    • the LinkedList throws an ArrayIndexOutOfBoundsException if you're lucky enough.

Am I overlooking something?

Would you support this feature in your collection (meant for general use)?

maaartinus
  • 44,714
  • 32
  • 161
  • 320

1 Answers1

2

From the JAVA DOC of toArray()

This implementation returns an array containing all the elements returned by this collection's iterator, in the same order, stored in consecutive elements of the array, starting with index 0. The length of the returned array is equal to the number of elements returned by the iterator, even if the size of this collection changes during iteration, as might happen if the collection permits concurrent modification during iteration.The size method is called only as an optimization hint; the correct result is returned even if the iterator returns a different number of elements.

Sage
  • 15,290
  • 3
  • 33
  • 38
  • Sorry, I'm removing my question as a duplicate of http://stackoverflow.com/questions/8401644/whats-the-usage-of-the-code-in-the-implementation-of-abstractcollections-toarr?rq=1 – maaartinus Oct 18 '13 at 11:00
  • I am not so sure of it. I have not posted a question yet and i don't know how to remove it. Thanks :) – Sage Oct 18 '13 at 11:07
  • @maaartinus: see this [post](http://meta.stackexchange.com/a/42297) for delete answer – Aniket Kulkarni Oct 18 '13 at 11:14
  • @Aniket: Forget it, nobody complained about a duplicate (and I had't found it before), so what. ;) – maaartinus Nov 03 '13 at 11:58