java - 为什么 AbstractCollection.toArray() 处理大小更改的情况?

标签 java arrays collections concurrency

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/

相关文章:

java - Exception() 的用例

python - 合并数组和绘图

java - 在流中存储新实例

forms - MVC 3 - 将 FormCollection 解析为模型

java - 在Android设备上使用Java/Kotlin检测音频文件(amr)中的静音

java 8 动态链接时可以使用累加器吗

java - 线程上下文切换是如何完成的?

python - 在字典中查找最接近的值

c - 我有一个c练习

java - 有任何集合对象可以保存两个以上元素的组合列表吗?