1 /* 2 * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 package java.util; 26 27 import java.util.function.IntConsumer; 28 import java.util.function.IntSupplier; 29 import java.util.function.Supplier; 30 import java.util.stream.IntStream; 31 32 /** 33 * A container object which may or may not contain an {@code int} value. If a 34 * value is present, {@code isPresent()} returns {@code true} and 35 * {@code getAsInt()} returns the value. 36 * 37 * <p>Additional methods that depend on the presence or absence of a contained 38 * value are provided, such as {@link #orElse(int) orElse()} 39 * (returns a default value if no value is present) and 40 * {@link #ifPresent(java.util.function.IntConsumer) ifPresent()} (performs an 41 * action if a value is present). 42 * 43 * <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a> 44 * class; use of identity-sensitive operations (including reference equality 45 * ({@code ==}), identity hash code, or synchronization) on instances of 46 * {@code OptionalInt} may have unpredictable results and should be avoided. 47 * 48 * @since 1.8 49 */ 50 public final class OptionalInt { 51 /** 52 * Common instance for {@code empty()}. 53 */ 54 private static final OptionalInt EMPTY = new OptionalInt(); 55 56 /** 57 * If true then the value is present, otherwise indicates no value is present 58 */ 59 private final boolean isPresent; 60 private final int value; 61 62 /** 63 * Construct an empty instance. 64 * 65 * @implNote Generally only one empty instance, {@link OptionalInt#EMPTY}, 66 * should exist per VM. 67 */ 68 private OptionalInt() { 69 this.isPresent = false; 70 this.value = 0; 71 } 72 73 /** 74 * Returns an empty {@code OptionalInt} instance. No value is present for 75 * this {@code OptionalInt}. 76 * 77 * @apiNote 78 * Though it may be tempting to do so, avoid testing if an object is empty 79 * by comparing with {@code ==} against instances returned by 80 * {@code OptionalInt.empty()}. There is no guarantee that it is a singleton. 81 * Instead, use {@link #isPresent()}. 82 * 83 * @return an empty {@code OptionalInt} 84 */ 85 public static OptionalInt empty() { 86 return EMPTY; 87 } 88 89 /** 90 * Construct an instance with the described value. 91 * 92 * @param value the int value to describe 93 */ 94 private OptionalInt(int value) { 95 this.isPresent = true; 96 this.value = value; 97 } 98 99 /** 100 * Returns an {@code OptionalInt} describing the given value. 101 * 102 * @param value the value to describe 103 * @return an {@code OptionalInt} with the value present 104 */ 105 public static OptionalInt of(int value) { 106 return new OptionalInt(value); 107 } 108 109 /** 110 * Equivalent to {@link #getWhenPresent()}. 111 * If a value is present, returns the value, otherwise throws 112 * {@code NoSuchElementException}. 113 * 114 * @deprecated 115 * This method's name {@code getAsInt} makes it the obvious method to 116 * call to retrieve the value from this {@code OptionalInt}. However, it has 117 * no mechanism to avoid an exception if this {@code OptionalInt} is empty. 118 * This tends to lead to code that mishandles empty {@code OptionalInt} 119 * values. Consider using other methods that handle the case where 120 * the {@code OptionalInt} might be empty, such as 121 * {@link #ifPresent(java.util.function.IntConsumer) ifPresent()} 122 * and related methods, and 123 * {@link #orElse(int) orElse()} and related methods. 124 * Use {@link getWhenPresent()} when it is known that a value is 125 * always present. 126 * 127 * @return the value described by this {@code OptionalInt} 128 * @throws NoSuchElementException if no value is present 129 * @see OptionalInt#isPresent() 130 */ 131 @Deprecated(since="9") 132 public int getAsInt() { 133 return getWhenPresent(); 134 } 135 136 /** 137 * If a value is present, returns the value, otherwise throws 138 * {@code NoSuchElementException}. 139 * 140 * @apiNote 141 * Use this method only when it is known that a value is always present. 142 * 143 * @return the value described by this {@code OptionalInt} 144 * @throws NoSuchElementException if no value is present 145 * @see OptionalInt#isPresent() 146 */ 147 public int getWhenPresent() { 148 if (!isPresent) { 149 throw new NoSuchElementException("No value present"); 150 } 151 return value; 152 } 153 154 /** 155 * If a value is present, returns {@code true}, otherwise {@code false}. 156 * 157 * @return {@code true} if a value is present, otherwise {@code false} 158 */ 159 public boolean isPresent() { 160 return isPresent; 161 } 162 163 /** 164 * If a value is present, performs the given action with the value, 165 * otherwise does nothing. 166 * 167 * @param action the action to be performed, if a value is present 168 * @throws NullPointerException if value is present and the given action is 169 * {@code null} 170 */ 171 public void ifPresent(IntConsumer action) { 172 if (isPresent) { 173 action.accept(value); 174 } 175 } 176 177 /** 178 * If a value is present, performs the given action with the value, 179 * otherwise performs the given empty-based action. 180 * 181 * @param action the action to be performed, if a value is present 182 * @param emptyAction the empty-based action to be performed, if no value is 183 * present 184 * @throws NullPointerException if a value is present and the given action 185 * is {@code null}, or no value is present and the given empty-based 186 * action is {@code null}. 187 * @since 9 188 */ 189 public void ifPresentOrElse(IntConsumer action, Runnable emptyAction) { 190 if (isPresent) { 191 action.accept(value); 192 } else { 193 emptyAction.run(); 194 } 195 } 196 197 /** 198 * If a value is present, returns a sequential {@link IntStream} containing 199 * only that value, otherwise returns an empty {@code IntStream}. 200 * 201 * @apiNote 202 * This method can be used to transform a {@code Stream} of optional 203 * integers to an {@code IntStream} of present integers: 204 * <pre>{@code 205 * Stream<OptionalInt> os = .. 206 * IntStream s = os.flatMapToInt(OptionalInt::stream) 207 * }</pre> 208 * 209 * @return the optional value as an {@code IntStream} 210 * @since 9 211 */ 212 public IntStream stream() { 213 if (isPresent) { 214 return IntStream.of(value); 215 } else { 216 return IntStream.empty(); 217 } 218 } 219 220 /** 221 * If a value is present, returns the value, otherwise returns 222 * {@code other}. 223 * 224 * @param other the value to be returned, if no value is present 225 * @return the value, if present, otherwise {@code other} 226 */ 227 public int orElse(int other) { 228 return isPresent ? value : other; 229 } 230 231 /** 232 * If a value is present, returns the value, otherwise returns the result 233 * produced by the supplying function. 234 * 235 * @param supplier the supplying function that produces a value to be returned 236 * @return the value, if present, otherwise the result produced by the 237 * supplying function 238 * @throws NullPointerException if no value is present and the supplying 239 * function is {@code null} 240 */ 241 public int orElseGet(IntSupplier supplier) { 242 return isPresent ? value : supplier.getAsInt(); 243 } 244 245 /** 246 * If a value is present, returns the value, otherwise throws an exception 247 * produced by the exception supplying function. 248 * 249 * @apiNote 250 * A method reference to the exception constructor with an empty argument 251 * list can be used as the supplier. For example, 252 * {@code IllegalStateException::new} 253 * 254 * @param <X> Type of the exception to be thrown 255 * @param exceptionSupplier the supplying function that produces an 256 * exception to be thrown 257 * @return the value, if present 258 * @throws X if no value is present 259 * @throws NullPointerException if no value is present and the exception 260 * supplying function is {@code null} 261 */ 262 public<X extends Throwable> int orElseThrow(Supplier<? extends X> exceptionSupplier) throws X { 263 if (isPresent) { 264 return value; 265 } else { 266 throw exceptionSupplier.get(); 267 } 268 } 269 270 /** 271 * Indicates whether some other object is "equal to" this 272 * {@code OptionalInt}. The other object is considered equal if: 273 * <ul> 274 * <li>it is also an {@code OptionalInt} and; 275 * <li>both instances have no value present or; 276 * <li>the present values are "equal to" each other via {@code ==}. 277 * </ul> 278 * 279 * @param obj an object to be tested for equality 280 * @return {@code true} if the other object is "equal to" this object 281 * otherwise {@code false} 282 */ 283 @Override 284 public boolean equals(Object obj) { 285 if (this == obj) { 286 return true; 287 } 288 289 if (!(obj instanceof OptionalInt)) { 290 return false; 291 } 292 293 OptionalInt other = (OptionalInt) obj; 294 return (isPresent && other.isPresent) 295 ? value == other.value 296 : isPresent == other.isPresent; 297 } 298 299 /** 300 * Returns the hash code of the value, if present, otherwise {@code 0} 301 * (zero) if no value is present. 302 * 303 * @return hash code value of the present value or {@code 0} if no value is 304 * present 305 */ 306 @Override 307 public int hashCode() { 308 return isPresent ? Integer.hashCode(value) : 0; 309 } 310 311 /** 312 * Returns a non-empty string representation of this {@code OptionalInt} 313 * suitable for debugging. The exact presentation format is unspecified and 314 * may vary between implementations and versions. 315 * 316 * @implSpec 317 * If a value is present the result must include its string representation 318 * in the result. Empty and present {@code OptionalInt}s must be 319 * unambiguously differentiable. 320 * 321 * @return the string representation of this instance 322 */ 323 @Override 324 public String toString() { 325 return isPresent 326 ? String.format("OptionalInt[%s]", value) 327 : "OptionalInt.empty"; 328 } 329 }