JDK8 Optional 用法记录
Posted amberbar
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDK8 Optional 用法记录相关的知识,希望对你有一定的参考价值。
Optional
of 与 ofNullable 的区别
/**
* Returns an {@code Optional} with the specified present non-null value.
*
* @param <T> the class of the value
* @param value the value to be present, which must be non-null
* @return an {@code Optional} with the value present
* @throws NullPointerException if value is null
*/
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an empty {@code Optional}.
*
* @param <T> the class of the value
* @param value the possibly-null value to describe
* @return an {@code Optional} with a present value if the specified value
* is non-null, otherwise an empty {@code Optional}
*/
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
- of 不允许为null
- ofNullable 允许为null
以上是关于JDK8 Optional 用法记录的主要内容,如果未能解决你的问题,请参考以下文章