< prev index next >

src/java.base/share/classes/java/util/Optional.java

Print this page
rev 17011 : 8167981: Optional: add notes explaining intended use
Reviewed-by: XXX

@@ -1,7 +1,7 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
  * under the terms of the GNU General Public License version 2 only, as
  * published by the Free Software Foundation.  Oracle designates this

@@ -44,10 +44,17 @@
  * <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a>
  * class; use of identity-sensitive operations (including reference equality
  * ({@code ==}), identity hash code, or synchronization) on instances of
  * {@code Optional} may have unpredictable results and should be avoided.
  *
+ * @apiNote
+ * {@code Optional} is primarily intended for use as a method return type where
+ * there is a clear need to represent "no result," and where using {@code null}
+ * is likely to cause errors. A variable whose type is {@code Optional} should
+ * never itself be {@code null}; it should always point to an {@code Optional}
+ * instance.
+ *
  * @param <T> the type of value
  * @since 1.8
  */
 public final class Optional<T> {
     /**

@@ -127,10 +134,16 @@
 
     /**
      * If a value is present, returns the value, otherwise throws
      * {@code NoSuchElementException}.
      *
+     * @apiNote
+     * The methods {@link #orElse(java.lang.Object) orElse()} and
+     * {@link #orElseGet(java.util.function.Supplier) orElseGet()}
+     * are generally preferable to this method, as they return a substitute
+     * value if the value is absent, instead of throwing an exception.
+     *
      * @return the non-{@code null} value described by this {@code Optional}
      * @throws NoSuchElementException if no value is present
      * @see Optional#isPresent()
      */
     public T get() {
< prev index next >