可选与空.Java 8 中 Optional 的目的是什么? [英] Optional vs. null. What is the purpose of Optional in Java 8?

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

问题描述

在 Java 8 中,您可以返回 Optional 而不是 null.Java 8 文档说 Optional 是一个容器对象,它可能包含也可能不包含非空值.如果存在一个值,isPresent() 将返回 true,get() 将返回该值."

In Java 8 you can return an Optional instead of a null. Java 8 documentation says that an Optional is "A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value."

在实践中,为什么这很有用?另外,是否有首选使用 null 的情况?性能怎么样?

In practice, why is this useful? Also, is there any case where using null would be preferred? What about performance?

推荐答案

在实践中,为什么这很有用?

In practice, why is this useful?

例如,假设您有这个整数流并且您正在进行过滤:

For example let's say you have this stream of integers and you're doing a filtering:

int x = IntStream.of(1, -3, 5)
                 .filter(x -> x % 2 == 0)
                 .findFirst(); //hypothetical assuming that there's no Optional in the API

您事先并不知道过滤操作会删除 Stream 中的所有值.

You don't know in advance that the filter operation will remove all the values in the Stream.

假设 API 中没有 Optional.在这种情况下,findFirst 应该返回什么?

Assume that there would be no Optional in the API. In this case, what should findFirst return?

唯一可能的方法是抛出一个异常,例如 NoSuchElementException,这在 IMO 相当烦人,因为我认为它不应该停止你的程序的执行(或者你有捕获异常,也不是很方便)并且过滤标准可能比这更复杂.

The only possible way would be to throw an exception such as NoSuchElementException, which is IMO rather annoying, as I don't think it should stop the execution of your program (or you'd have to catch the exception, not very convenient either) and the filtering criteria could be more complex than that.

使用Optional,由调用者检查Optional 是否为空(即您的计算是否产生了一个值).

With the use of Optional, it's up to the caller to check whether the Optional is empty or not (i.e if your computation resulted in a value or not).

使用引用类型,您还可以返回 null(但 null 可能是您仅过滤 null 值的情况下的可能值;所以我们回到异常情况).

With reference type, you could also return null (but null could be a possible value in the case you filter only null values; so we're back to the exception case).

关于非流用法,除了防止 NPE 之外,我认为设计一个更明确的 API 说明值可能存在或不存在也有帮助.例如考虑这个类:

Concerning non-stream usages, in addition to prevent NPE, I think it also helps to design a more explicit API saying that the value may be present or not. For example consider this class:

class Car {
   RadioCar radioCar; //may be null or not 
   public Optional<RadioCar> getRadioCar() {
        return Optional.ofNullable(radioCar);
   }
}

在这里,您清楚地告诉来电者,汽车中的收音机是可选的,它可能存在,也可能不存在.

Here you are clearly saying to the caller that the radio in the car is optional, it might be or not there.

这篇关于可选与空.Java 8 中 Optional 的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆