本文介绍了Java 8可选.为什么of和of可以为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Java 8的可选,其目的是解决NullPointerException异常.

I have a question regarding Java 8's Optional, the purpose of which is to tackle NullPointerException exceptions.

问题是,让我们选择这两种类型的原因是什么?

The question is, what is the reason for having both types to let us choose:

Optional.of(T value)     <-----non-null value, null value will throw NPE
Optional.ofNullable(T value)   <----- nullable value

因为我期望的是,当我使用时:

Because what I expect is, when I use:

Optional.of(nullValue);

它不会抛出NullPointerException.

在回答后扩大了我的问题:

Expanded my question after some replies:

为什么人们会选择Optional而不是普通的if-else进行空检查?

Why would people opt for Optional instead of normal if-else for null checking?

推荐答案

Optional.of 会明确地读取该信息:

The javadoc of Optional.of reads that explicitly :

@throws NullPointerException if value is null

,这就是使用Optional.ofNullable处理您所期望的案件的要求,这是一小段代码,例如:

and that is where the requirement of handling the cases as expected by you comes into picture with the use of Optional.ofNullable which is a small block of code as :

public static <T> Optional<T> ofNullable(T value) {
    return value == null ? empty() : of(value); // 'Optional.of'
}

也就是说,在应用程序设计中仍然会选择[strong] 来决定选择一个选项还是另一个选项.

That said, the decision of choosing one over the other would still reside with the application design as if your value could possibly be null or not.

在您的期望中,这不是Optional的实际意图. API注释进一步阐明了这一点(格式化我的格式):

On your expectation part, that was not what the Optional was actually intended for. The API note clarifies this further (formatting mine):


旁边:只是为了清楚地指出,选择当然会隐式地让您定义是否应在运行时抛出NPE.它不是在编译时确定的.

Aside: Just to call it out clearly, that the choice would of course implicitly let you define if an NPE should be thrown at runtime or not. It's not determined at the compile time though.

这篇关于Java 8可选.为什么of和of可以为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 08:11
查看更多