gpt4 book ai didi

java - AbstractCollection 的 toArray 方法实现中代码的用途是什么

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:08 24 4
gpt4 key购买 nike

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;
}

这里是AbstractCollection.toArray方法的实现代码。

if (! it.hasNext()) // fewer elements than expected
return Arrays.copyOf(r, i);

我不明白上面代码的用法。我怀疑代码用于避免在调用方法时更改大小。所以我有两个问题:

  1. 我怀疑的是对还是错?如果错了,这段代码有什么用?
  2. 如果为真,在调用该方法时什么情况下会导致尺寸发生变化?

最佳答案

好吧,方法的 javadoc 说明了一切:

 /**
* {@inheritDoc}
*
* <p>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 {@code 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 {@code size} method is
* called only as an optimization hint; the correct result is returned
* even if the iterator returns a different number of elements.
*
* <p>This method is equivalent to:
*
* <pre> {@code
* List<E> list = new ArrayList<E>(size());
* for (E e : this)
* list.add(e);
* return list.toArray();
* }</pre>
*/

我发现这里有两件有趣的事情要提:

  1. 是的,您是对的,正如 javadoc 所说,即使同时修改了 Collection,此方法也准备好正确返回。这就是为什么初始大小只是一个提示。迭代器的使用还确保避免“并发修改”异常。

  2. 很容易想象一种多线程情况,其中一个线程从集合中添加/删除元素,而另一个线程调用集合中的“toArray”方法。在这种情况下,如果 Collection 不是线程安全的(比如通过 Collections.synchronizedCollection(...) 方法获得,或者通过手动创建同步访问代码),你会遇到这样的情况它被同时修改和 toArray-ed。

关于java - AbstractCollection 的 toArray 方法实现中代码的用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8401644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com