为什么我可以将并行流收集到任意大型数组而不是顺序流? [英] Why can I collect a parallel stream to an arbitrarily large array but not a sequential stream?

查看:114
本文介绍了为什么我可以将并行流收集到任意大型数组而不是顺序流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过回答这个问题,我遇到了一个特殊的功能。下面的代码按照我的假设工作(现有数组中的前两个值将被覆盖):

From answering this question, I ran into a peculiar feature. The following code works as I assumed it would (the first two values within the existing array would be overridden):

Integer[] newArray = Stream.of(7, 8)
                           .parallel()
                           .toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6});

System.out.println(Arrays.toString(newArray));

输出:

[7, 8, 3, 4, 5, 6]

然而,尝试这与顺序流抛出 IllegalStateException

However, attempting this with a sequential stream throws an IllegalStateException:

Integer[] newArray = Stream.of(7, 8)
                           .toArray(i -> new Integer[] {1, 2, 3, 4, 5, 6});

System.out.println(Arrays.toString(newArray));

输出:

Exception in thread "main" java.lang.IllegalStateException: Begin size 2 is not equal to fixed size 6
    at java.base/java.util.stream.Nodes$FixedNodeBuilder.begin(Nodes.java:1222)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:483)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:550)
    at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
    at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:517)
    at test/test.Test.main(Test.java:30)

我很好奇为什么顺序流不会像并行流那样覆盖数组的元素。我搜索了一下,但无法找到有关此的文档,但我认为它存在于某个地方。

I'm curious as to why the sequential stream does not overwrite elements of the array as the parallel stream does. I searched around a bit and was not able to find documentation regarding this, but I assume it exists somewhere.

推荐答案

generator 函数是 required 生成所需类型的新数组和提供的长度。如果您不遵守规范,则行为未定义。

The generator function is required to produce "a new array of the desired type and the provided length." If you don't comply with the spec, behavior is undefined.

这篇关于为什么我可以将并行流收集到任意大型数组而不是顺序流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆