gpt4 book ai didi

java - 为什么Stream#toList的默认实现似乎过于复杂/不够理想?

转载 作者:行者123 更新时间:2023-12-03 15:20:59 25 4
gpt4 key购买 nike

在查看Stream#toList的实现时,我只是注意到它看起来过于复杂和欠佳。
就像在上面的javadoc中提到的那样,大多数default实现都没有使用此Stream实现,但是,我认为可能是其他原因。
资料来源

/**
* Accumulates the elements of this stream into a {@code List}. The elements in
* the list will be in this stream's encounter order, if one exists. The returned List
* is unmodifiable; calls to any mutator method will always cause
* {@code UnsupportedOperationException} to be thrown. There are no
* guarantees on the implementation type or serializability of the returned List.
*
* <p>The returned instance may be <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>.
* Callers should make no assumptions about the identity of the returned instances.
* Identity-sensitive operations on these instances (reference equality ({@code ==}),
* identity hash code, and synchronization) are unreliable and should be avoided.
*
* <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
*
* @apiNote If more control over the returned object is required, use
* {@link Collectors#toCollection(Supplier)}.
*
* @implSpec The implementation in this interface returns a List produced as if by the following:
* <pre>{@code
* Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray())))
* }</pre>
*
* @implNote Most instances of Stream will override this method and provide an implementation
* that is highly optimized compared to the implementation in this interface.
*
* @return a List containing the stream elements
*
* @since 16
*/
@SuppressWarnings("unchecked")
default List<T> toList() {
return (List<T>) Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray())));
}
我对什么会更好的想法
return (List<T>) Collections.unmodifiableList(Arrays.asList(this.toArray()));
甚至
return Arrays.asList(this.toArray()));
IntelliJ的建议
return (List<T>) List.of(this.toArray());
是否有充分的理由在JDK源代码中实现?

最佳答案

可以实现toArray方法来返回一个数组,然后该数组随后发生突变,这将有效地使返回的列表不可变。这就是为什么通过创建新的ArrayList进行显式复制的原因。
本质上是防御性副本。
斯图尔特·马克斯(Stuart Marks)在review of this API期间也对此进行了讨论:

As written it's true that the default implementation does perform apparently redundant copies, but we can't be assured that toArray() actually returns a freshly created array. Thus, we wrap it using Arrays.asList and then copy it using the ArrayList constructor. This is unfortunate but necessary to avoid situations where someone could hold a reference to the internal array of a List, allowing modification of a List that's supposed to be unmodifiable.

关于java - 为什么Stream#toList的默认实现似乎过于复杂/不够理想?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66946013/

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