可选与空。Java 8 中 Optional 的目的是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28746482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Optional vs. null. What is the purpose of Optional in Java 8?
提问by Jadiel de Armas
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."
在 Java 8 中,您可以返回一个Optional
而不是一个null
。Java 8 文档说 Optional 是“一个容器对象,它可能包含也可能不包含非空值。如果存在一个值,isPresent() 将返回 true,get() 将返回该值。”
In practice, why is this useful?
Also, is there any case where using null
would be preferred? What about performance?
在实践中,为什么这很有用?另外,有没有null
更喜欢使用的情况?性能呢?
采纳答案by Alexis C.
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
You don't know in advance that the filter operation will remove all the values in the Stream.
您事先不知道过滤操作会删除 Stream 中的所有值。
Assume that there would be no Optional in the API. In this case, what should findFirst
return?
假设 API 中没有 Optional。在这种情况下,应该findFirst
返回什么?
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.
唯一可能的方法是抛出一个异常,例如NoSuchElementException
,这是 IMO 相当烦人的,因为我认为它不应该停止您的程序的执行(或者您必须捕获异常,也不是很方便)和过滤标准可能比这更复杂。
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).
使用 时Optional
,由调用者检查 是否Optional
为空(即您的计算是否产生了值)。
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).
使用引用类型,您也可以返回null
(但null
在您只过滤null
值的情况下可能是一个可能的值;所以我们回到异常情况)。
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:
关于非流用法,除了防止 NPE 之外,我认为设计一个更明确的 API 说明该值可能存在与否也有帮助。例如考虑这个类:
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.
在这里,您清楚地对来电者说,汽车中的收音机是可选的,它可能存在,也可能不存在。
回答by user3728064
Optional helps you to handle variables as available or not available and avoid check null references.
Optional 可帮助您处理可用或不可用的变量,并避免检查空引用。
回答by OldCurmudgeon
When Java was first designed it was common practice to use a special value, usually called null
to indicate special circumstances like I couldn't find what you were looking for. This practice was adopted by Java.
最初设计 Java 时,通常的做法是使用特殊值,通常调用它null
来指示特殊情况,例如I can't find what you are looking。Java 采用了这种做法。
Since then it has been suggested that this practice should be considered an anti-pattern, especially for objects, because it means that you have to litter your code with null checks to achieve reliability and stability. It is also a pain when you want to put null
into a collection for example.
从那时起,有人建议将这种做法视为一种反模式,尤其是对于对象,因为这意味着您必须使用空检查来乱丢代码以实现可靠性和稳定性。例如,当您想放入null
一个集合时,这也是一种痛苦。
The modern attitude is to use a special object that may or may not hold a value. This way you can safely create one and just not fill it with anything. Here you are seeing Java 8 encouraging this best-practice by providing an Optional
object.
现代的态度是使用一个可能有也可能没有价值的特殊对象。这样你就可以安全地创建一个,而不是用任何东西填充它。在这里,您可以看到 Java 8 通过提供一个Optional
对象来鼓励这种最佳实践。