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;
}
恕我直言,“准备好看到更多或更少的元素”这部分纯粹是无意义的:
- 如果集契约(Contract)时发生变化,迭代器无论如何都会抛出
ConcurrentModification
异常。 - 我还没有发现任何非并发子类支持这一点,特别是
ArrayList
使用Arrays.copyOf(elementData, size)
,它可以(由于可见性问题)复制一堆null
调整大小时的数据,- 如果您足够幸运,
LinkedList
会抛出ArrayIndexOutOfBoundsException
。
我是否忽略了什么?
您会在您的 Collection 中支持此功能(用于一般用途)吗?
最佳答案
来自 toArray() 的 JAVA DOC
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.
关于java - 为什么 AbstractCollection.toArray() 处理大小更改的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19447738/