1 /*
2 * Copyright (c) 2012, 2020, 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.
34 * If a value is present, {@code isPresent()} returns {@code true}. If no
35 * value is present, the object is considered <i>empty</i> and
36 * {@code isPresent()} returns {@code false}.
37 *
38 * <p>Additional methods that depend on the presence or absence of a contained
39 * value are provided, such as {@link #orElse(int) orElse()}
40 * (returns a default value if no value is present) and
41 * {@link #ifPresent(IntConsumer) ifPresent()} (performs an
42 * action if a value is present).
43 *
44 * <p>This is a <a href="{@docRoot}/java.base/java/lang/doc-files/ValueBased.html">value-based</a>
45 * class; programmers should treat instances that are {@linkplain #equals(Object) equal} 46 * as interchangeable and should not use instances for synchronization, mutexes, or 47 * with {@linkplain java.lang.ref.Reference object references}. 48 * 49 * <div class="preview-block"> 50 * <div class="preview-comment"> 51 * When preview features are enabled, {@code OptionalInt} is a {@linkplain Class#isValue value class}. 52 * Use of value class instances for synchronization, mutexes, or with 53 * {@linkplain java.lang.ref.Reference object references} result in 54 * {@link IdentityException}. 55 * </div> 56 * </div>
57 *
58 * @apiNote
59 * {@code OptionalInt} is primarily intended for use as a method return type where
60 * there is a clear need to represent "no result." A variable whose type is
61 * {@code OptionalInt} should never itself be {@code null}; it should always point
62 * to an {@code OptionalInt} instance.
63 *
64 * @since 1.8
65 */
66 @jdk.internal.ValueBased
67 @jdk.internal.MigratedValueClass
68 public final class OptionalInt {
69 /**
70 * Common instance for {@code empty()}.
71 */
72 private static final OptionalInt EMPTY = new OptionalInt();
73
74 /**
75 * If true then the value is present, otherwise indicates no value is present
76 */
77 private final boolean isPresent;
78 private final int value;
79
80 /**
81 * Construct an empty instance.
82 *
83 * @implNote Generally only one empty instance, {@link OptionalInt#EMPTY},
84 * should exist per VM.
85 */
86 private OptionalInt() {
87 this.isPresent = false;
88 this.value = 0;
89 }
90
91 /**
92 * Returns an empty {@code OptionalInt} instance. No value is present for
93 * this {@code OptionalInt}.
94 *
95 * @apiNote
96 * Though it may be tempting to do so, avoid testing if an object is empty
97 * by comparing with {@code ==} or {@code !=} against instances returned by
98 * {@code OptionalInt.empty()}. There is no guarantee that it is a singleton.
99 * Instead, use {@link #isEmpty()} or {@link #isPresent()}.
100 *
101 * @return an empty {@code OptionalInt}
102 */
103 public static OptionalInt empty() {
104 return EMPTY;
105 }
106
107 /**
108 * Construct an instance with the described value.
109 *
110 * @param value the int value to describe
111 */
112 private OptionalInt(int value) {
113 this.isPresent = true;
114 this.value = value;
115 }
116
117 /**
118 * Returns an {@code OptionalInt} describing the given value.
119 *
120 * @param value the value to describe
121 * @return an {@code OptionalInt} with the value present
122 */
123 public static OptionalInt of(int value) {
124 return new OptionalInt(value);
125 }
126
127 /**
128 * If a value is present, returns the value, otherwise throws
129 * {@code NoSuchElementException}.
130 *
131 * @apiNote
132 * The preferred alternative to this method is {@link #orElseThrow()}.
133 *
134 * @return the value described by this {@code OptionalInt}
135 * @throws NoSuchElementException if no value is present
136 */
137 public int getAsInt() {
138 if (!isPresent) {
139 throw new NoSuchElementException("No value present");
140 }
141 return value;
142 }
143
144 /**
145 * If a value is present, returns {@code true}, otherwise {@code false}.
146 *
147 * @return {@code true} if a value is present, otherwise {@code false}
148 */
149 public boolean isPresent() {
150 return isPresent;
151 }
152
153 /**
154 * If a value is not present, returns {@code true}, otherwise
155 * {@code false}.
156 *
157 * @return {@code true} if a value is not present, otherwise {@code false}
158 * @since 11
159 */
160 public boolean isEmpty() {
161 return !isPresent;
162 }
163
164 /**
165 * If a value is present, performs the given action with the value,
166 * otherwise does nothing.
167 *
168 * @param action the action to be performed, if a value is present
169 * @throws NullPointerException if value is present and the given action is
170 * {@code null}
171 */
172 public void ifPresent(IntConsumer action) {
173 if (isPresent) {
174 action.accept(value);
175 }
176 }
177
178 /**
179 * If a value is present, performs the given action with the value,
180 * otherwise performs the given empty-based action.
181 *
182 * @param action the action to be performed, if a value is present
183 * @param emptyAction the empty-based action to be performed, if no value is
184 * present
185 * @throws NullPointerException if a value is present and the given action
186 * is {@code null}, or no value is present and the given empty-based
187 * action is {@code null}.
188 * @since 9
189 */
190 public void ifPresentOrElse(IntConsumer action, Runnable emptyAction) {
191 if (isPresent) {
192 action.accept(value);
193 } else {
194 emptyAction.run();
195 }
196 }
197
198 /**
199 * If a value is present, returns a sequential {@link IntStream} containing
200 * only that value, otherwise returns an empty {@code IntStream}.
201 *
202 * @apiNote
203 * This method can be used to transform a {@code Stream} of optional
204 * integers to an {@code IntStream} of present integers:
205 * <pre>{@code
206 * Stream<OptionalInt> os = ..
207 * IntStream s = os.flatMapToInt(OptionalInt::stream)
208 * }</pre>
209 *
210 * @return the optional value as an {@code IntStream}
211 * @since 9
212 */
213 public IntStream stream() {
214 if (isPresent) {
215 return IntStream.of(value);
216 } else {
217 return IntStream.empty();
218 }
219 }
220
221 /**
222 * If a value is present, returns the value, otherwise returns
223 * {@code other}.
224 *
225 * @param other the value to be returned, if no value is present
226 * @return the value, if present, otherwise {@code other}
227 */
228 public int orElse(int other) {
229 return isPresent ? value : other;
230 }
231
232 /**
233 * If a value is present, returns the value, otherwise returns the result
234 * produced by the supplying function.
235 *
236 * @param supplier the supplying function that produces a value to be returned
237 * @return the value, if present, otherwise the result produced by the
238 * supplying function
239 * @throws NullPointerException if no value is present and the supplying
240 * function is {@code null}
241 */
242 public int orElseGet(IntSupplier supplier) {
243 return isPresent ? value : supplier.getAsInt();
244 }
245
246 /**
247 * If a value is present, returns the value, otherwise throws
248 * {@code NoSuchElementException}.
249 *
250 * @return the value described by this {@code OptionalInt}
251 * @throws NoSuchElementException if no value is present
252 * @since 10
253 */
254 public int orElseThrow() {
255 if (!isPresent) {
256 throw new NoSuchElementException("No value present");
257 }
258 return value;
259 }
260
261 /**
262 * If a value is present, returns the value, otherwise throws an exception
263 * produced by the exception supplying function.
264 *
265 * @apiNote
266 * A method reference to the exception constructor with an empty argument
267 * list can be used as the supplier. For example,
268 * {@code IllegalStateException::new}
269 *
270 * @param <X> Type of the exception to be thrown
271 * @param exceptionSupplier the supplying function that produces an
272 * exception to be thrown
273 * @return the value, if present
274 * @throws X if no value is present
275 * @throws NullPointerException if no value is present and the exception
276 * supplying function is {@code null}
277 */
278 public<X extends Throwable> int orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
279 if (isPresent) {
280 return value;
281 } else {
282 throw exceptionSupplier.get();
283 }
284 }
285
286 /**
287 * Indicates whether some other object is "equal to" this
288 * {@code OptionalInt}. The other object is considered equal if:
289 * <ul>
290 * <li>it is also an {@code OptionalInt} and;
291 * <li>both instances have no value present or;
292 * <li>the present values are "equal to" each other via {@code ==}.
293 * </ul>
294 *
295 * @param obj an object to be tested for equality
296 * @return {@code true} if the other object is "equal to" this object
297 * otherwise {@code false}
298 */
299 @Override
300 public boolean equals(Object obj) {
301 if (this == obj) {
302 return true;
303 }
304
305 return obj instanceof OptionalInt other
306 && (isPresent && other.isPresent
307 ? value == other.value
308 : isPresent == other.isPresent);
309 }
310
311 /**
312 * Returns the hash code of the value, if present, otherwise {@code 0}
313 * (zero) if no value is present.
314 *
315 * @return hash code value of the present value or {@code 0} if no value is
316 * present
317 */
318 @Override
319 public int hashCode() {
320 return isPresent ? Integer.hashCode(value) : 0;
321 }
322
323 /**
324 * Returns a non-empty string representation of this {@code OptionalInt}
325 * suitable for debugging. The exact presentation format is unspecified and
326 * may vary between implementations and versions.
327 *
328 * @implSpec
329 * If a value is present the result must include its string representation
330 * in the result. Empty and present {@code OptionalInt}s must be
331 * unambiguously differentiable.
332 *
333 * @return the string representation of this instance
334 */
335 @Override
336 public String toString() {
337 return isPresent
338 ? ("OptionalInt[" + value + "]")
339 : "OptionalInt.empty";
340 }
341 }
--- EOF ---