码迷,mamicode.com
首页 > 其他好文 > 详细

【JDK8】 Optional 用法记录

时间:2020-07-30 14:39:39      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:@param   option   empty   记录   throw   bin   point   throws   null   

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 用法记录

标签:@param   option   empty   记录   throw   bin   point   throws   null   

原文地址:https://www.cnblogs.com/amberbar/p/13356445.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!