如果找到的第一个元素为null,为什么findFirst()会抛出NullPointerException? [英] Why does findFirst() throw a NullPointerException if the first element it finds is null?
问题描述
为什么抛出 java.lang.NullPointerException
?
List<String> strings = new ArrayList<>();
strings.add(null);
strings.add("test");
String firstString = strings.stream()
.findFirst() // Exception thrown here
.orElse("StringWhenListIsEmpty");
//.orElse(null); // Changing the `orElse()` to avoid ambiguity
字符串
是 null
,这是一个完全可以接受的值。此外, findFirst()
返回可选,这对 findFirst()
更有意义,能够处理 null
s 。
The first item in strings
is null
, which is a perfectly acceptable value. Furthermore, findFirst()
returns an Optional, which makes even more sense for findFirst()
to be able to handle null
s.
编辑:更新 orElse()
更不明确。
推荐答案
原因是在回报中使用 Optional< T>
。可选不允许包含 null
。从本质上讲,它无法区分情况它不在那里和它在那里,但它被设置为 null
。
The reason for this is the use of Optional<T>
in the return. Optional is not allowed to contain null
. Essentially, it offers no way of distinguishing situations "it's not there" and "it's there, but it is set to null
".
这就是为什么文档在中选择
: null
时明确禁止这种情况:findFirst()
That's why the documentation explicitly prohibits the situation when null
is selected in findFirst()
:
抛出:
NullPointerException
- 如果选择的元素是 null
NullPointerException
- if the element selected is null
这篇关于如果找到的第一个元素为null,为什么findFirst()会抛出NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!