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() 能够处理 nulls 更有意义.
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 nulls.
更新了 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?
基础教程推荐
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Maven:无效的目标版本:10 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
