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

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

问题描述

在Java 8中,您可以返回可选而不是 null 。 Java 8文档说可选是容器对象,它可能包含或不包含非空值。如果存在值,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.

使用可选,由调用者来检查是否可选是否为空(即如果您的计算结果是否为值)。

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 可能是一个可能的值c>值;所以我们回到例外情况)。

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.

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

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