Why does findFirst() throw a NullPointerException if the first element it finds is null?(如果 findFirst() 找到的第一个元素为 null,为什么会抛出 NullPointerException?)
问题描述
为什么会抛出 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
strings
中的第一项是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()
以减少歧义.
updated the orElse()
to be less ambiguous.
推荐答案
之所以会这样,是因为在返回中使用了Optional
.Optional 不允许包含 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
".
这就是为什么文档明确禁止在findFirst()
中选择null
的情况:
That's why the documentation explicitly prohibits the situation when null
is selected in findFirst()
:
投掷:
NullPointerException
- 如果选择的元素是 null
NullPointerException
- if the element selected is null
这篇关于如果 findFirst() 找到的第一个元素为 null,为什么会抛出 NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果 findFirst() 找到的第一个元素为 null,为什么会抛出 NullPointerException?


基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java Swing计时器未清除 2022-01-01