gpt4 book ai didi

java - 创建 Stream 后更改 Stream 源时 Stream 的行为

转载 作者:行者123 更新时间:2023-12-01 07:44:05 28 4
gpt4 key购买 nike

考虑下面的代码:

     List<Integer> l=new ArrayList<>();
l.add(23);l.add(45);l.add(90);

Stream<Integer> str=l.stream(); // mark A

l.add(111);
l=null;

System.out.println(str.collect(Collectors.toList())); // mark B

输出是:

[23, 45, 90, 111]

我在这里假设当在标记 B 处调用终端操作时,将评估标记 A 的 RHS这意味着最近的列表(包含元素“111”)正在被选中,但问题是为什么我们没有得到NullPointerException 这里..如果我们没有得到异常那么我们不应该得到“111”也在输出中......请帮忙。

最佳答案

the documentation 中明确说明了此行为:

For well-behaved stream sources, the source can be modified before the terminal operation commences and those modifications will be reflected in the covered elements. For example, consider the following code:

List<String> l = new ArrayList(Arrays.asList("one", "two"));
Stream<String> sl = l.stream();
l.add("three");
String s = sl.collect(joining(" "));

First a list is created consisting of two strings: "one"; and "two". Then a stream is created from that list. Next the list is modified by adding a third string: "three". Finally the elements of the stream are collected and joined together. Since the list was modified before the terminal collect operation commenced the result will be a string of "one two three". All the streams returned from JDK collections, and most other JDK classes, are well-behaved in this manner; for streams generated by other libraries, see Low-level stream construction for requirements for building well-behaved streams.

关于java - 创建 Stream 后更改 Stream 源时 Stream 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58092903/

28 4 0