1 /*
2 * Copyright (c) 2009, 2026, 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
26 package java.util;
27
28 import jdk.internal.javac.PreviewFeature;
29 import jdk.internal.util.Preconditions;
30 import jdk.internal.vm.annotation.ForceInline;
31
32 import java.util.function.Supplier;
33
34 /**
35 * This class consists of {@code static} utility methods for operating
36 * on objects, or checking certain conditions before operation. These utilities
37 * include {@code null}-safe or {@code null}-tolerant methods for computing the
38 * hash code of an object, returning a string for an object, comparing two
39 * objects, and checking if indexes or sub-range values are out of bounds.
40 *
41 * @since 1.7
42 */
43 public final class Objects {
44 private Objects() {
45 throw new AssertionError("No java.util.Objects instances for you!");
46 }
47
48 /**
49 * {@return {@code true} if the arguments are equal to each other
50 * and {@code false} otherwise}
51 * Consequently, if both arguments are {@code null}, {@code true}
52 * is returned. Otherwise, if the first argument is not {@code
53 * null}, equality is determined by calling the {@link
54 * Object#equals equals} method of the first argument with the
55 * second argument of this method. Otherwise, {@code false} is
56 * returned.
57 *
58 * @param a an object
59 * @param b an object to be compared with {@code a} for equality
60 * @see Object#equals(Object)
61 */
62 public static boolean equals(Object a, Object b) {
63 return (a == b) || (a != null && a.equals(b));
64 }
65
66 /**
67 * {@return {@code true} if the arguments are deeply equal to each other
68 * and {@code false} otherwise}
69 *
70 * Two {@code null} values are deeply equal. If both arguments are
71 * arrays, the algorithm in {@link Arrays#deepEquals(Object[],
72 * Object[]) Arrays.deepEquals} is used to determine equality.
73 * Otherwise, equality is determined by using the {@link
74 * Object#equals equals} method of the first argument.
75 *
76 * @param a an object
77 * @param b an object to be compared with {@code a} for deep equality
78 * @see Arrays#deepEquals(Object[], Object[])
79 * @see Objects#equals(Object, Object)
80 */
81 public static boolean deepEquals(Object a, Object b) {
82 if (a == b)
83 return true;
84 else if (a == null || b == null)
85 return false;
86 else
87 return Arrays.deepEquals0(a, b);
88 }
89
90 /**
91 * {@return the hash code of a non-{@code null} argument and 0 for
92 * a {@code null} argument}
93 *
94 * @param o an object
95 * @see Object#hashCode
96 */
97 public static int hashCode(Object o) {
98 return o != null ? o.hashCode() : 0;
99 }
100
101 /**
102 * {@return a hash code for a sequence of input values} The hash
103 * code is generated as if all the input values were placed into an
104 * array, and that array were hashed by calling {@link
105 * Arrays#hashCode(Object[])}.
106 *
107 * <p>This method is useful for implementing {@link
108 * Object#hashCode()} on objects containing multiple fields. For
109 * example, if an object that has three fields, {@code x}, {@code
110 * y}, and {@code z}, one could write:
111 *
112 * <blockquote><pre>
113 * @Override public int hashCode() {
114 * return Objects.hash(x, y, z);
115 * }
116 * </pre></blockquote>
117 *
118 * <b>Warning: When a single object reference is supplied, the returned
119 * value does not equal the hash code of that object reference.</b> This
120 * value can be computed by calling {@link #hashCode(Object)}.
121 *
122 * @param values the values to be hashed
123 * @see Arrays#hashCode(Object[])
124 * @see List#hashCode
125 */
126 public static int hash(Object... values) {
127 return Arrays.hashCode(values);
128 }
129
130 /**
131 * {@return the result of calling {@code toString} for a
132 * non-{@code null} argument and {@code "null"} for a
133 * {@code null} argument}
134 *
135 * @param o an object
136 * @see Object#toString
137 * @see String#valueOf(Object)
138 */
139 public static String toString(Object o) {
140 return String.valueOf(o);
141 }
142
143 /**
144 * {@return the result of calling {@code toString} on the first
145 * argument if the first argument is not {@code null} and the
146 * second argument otherwise}
147 *
148 * @param o an object
149 * @param nullDefault string to return if the first argument is
150 * {@code null}
151 * @see Objects#toString(Object)
152 */
153 public static String toString(Object o, String nullDefault) {
154 return (o != null) ? o.toString() : nullDefault;
155 }
156
157 /**
158 * {@return a string equivalent to the string returned by {@code
159 * Object.toString} if that method and {@code hashCode} are not
160 * overridden}
161 *
162 * @implNote
163 * This method constructs a string for an object without calling
164 * any overridable methods of the object.
165 *
166 * @implSpec
167 * The method returns a string equivalent to:<br>
168 * {@code o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o))}
169 *
170 * @param o an object
171 * @throws NullPointerException if the argument is null
172 * @see Object#toString
173 * @see System#identityHashCode(Object)
174 * @since 19
175 */
176 public static String toIdentityString(Object o) {
177 requireNonNull(o);
178 return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
179 }
180
181 /**
182 * {@return {@code true} if the object is a non-null reference
183 * to an {@linkplain Class#isIdentity() identity object}, otherwise {@code false}}
184 *
185 * @apiNote
186 * If the parameter is {@code null}, there is no object
187 * and hence no class to check for identity; the return is {@code false}.
188 * To test for a {@linkplain Class#isValue() value object} use:
189 * {@snippet type="java" :
190 * if (obj != null && !Objects.hasIdentity(obj)) {
191 * // obj is a non-null value object
192 * }
193 * }
194 * @param obj an object or {@code null}
195 * @since Valhalla
196 */
197 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
198 // @IntrinsicCandidate
199 public static boolean hasIdentity(Object obj) {
200 return (obj == null) ? false : obj.getClass().isIdentity();
201 }
202
203 /**
204 * {@return {@code true} if the object is a non-null reference
205 * to a {@linkplain Class#isValue() value object}, otherwise {@code false}}
206 *
207 * @param obj an object or {@code null}
208 * @since Valhalla
209 */
210 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
211 // @IntrinsicCandidate
212 public static boolean isValueObject(Object obj) {
213 return (obj == null) ? false : obj.getClass().isValue();
214 }
215
216 /**
217 * Checks that the specified object reference is an identity object.
218 *
219 * @param obj the object reference to check for identity
220 * @param <T> the type of the reference
221 * @return {@code obj} if {@code obj} is an identity object
222 * @throws NullPointerException if {@code obj} is {@code null}
223 * @throws IdentityException if {@code obj} is not an identity object
224 * @since Valhalla
225 */
226 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
227 @ForceInline
228 public static <T> T requireIdentity(T obj) {
229 Objects.requireNonNull(obj);
230 if (!hasIdentity(obj))
231 throw new IdentityException(obj.getClass());
232 return obj;
233 }
234
235 /**
236 * Checks that the specified object reference is an identity object.
237 *
238 * @param obj the object reference to check for identity
239 * @param message detail message to be used in the event that an
240 * {@code IdentityException} is thrown; may be null
241 * @param <T> the type of the reference
242 * @return {@code obj} if {@code obj} is an identity object
243 * @throws NullPointerException if {@code obj} is {@code null}
244 * @throws IdentityException if {@code obj} is not an identity object
245 * @since Valhalla
246 */
247 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
248 @ForceInline
249 public static <T> T requireIdentity(T obj, String message) {
250 Objects.requireNonNull(obj);
251 if (!hasIdentity(obj))
252 throw new IdentityException(message);
253 return obj;
254 }
255
256 /**
257 * Checks that the specified object reference is an identity object.
258 *
259 * @param obj the object reference to check for identity
260 * @param messageSupplier supplier of the detail message to be
261 * used in the event that an {@code IdentityException} is thrown; may be null
262 * @param <T> the type of the reference
263 * @return {@code obj} if {@code obj} is an identity object
264 * @throws NullPointerException if {@code obj} is {@code null}
265 * @throws IdentityException if {@code obj} is not an identity object
266 * @since Valhalla
267 */
268 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
269 @ForceInline
270 public static <T> T requireIdentity(T obj, Supplier<String> messageSupplier) {
271 Objects.requireNonNull(obj);
272 if (!hasIdentity(obj))
273 throw new IdentityException(messageSupplier == null ?
274 null : messageSupplier.get());
275 return obj;
276 }
277
278 /**
279 * {@return 0 if the arguments are identical and {@code
280 * c.compare(a, b)} otherwise}
281 * Consequently, if both arguments are {@code null} 0
282 * is returned.
283 *
284 * <p>Note that if one of the arguments is {@code null}, a {@code
285 * NullPointerException} may or may not be thrown depending on
286 * what ordering policy, if any, the {@link Comparator Comparator}
287 * chooses to have for {@code null} values.
288 *
289 * @param <T> the type of the objects being compared
290 * @param a an object
291 * @param b an object to be compared with {@code a}
292 * @param c the {@code Comparator} to compare the first two arguments
293 * @see Comparable
294 * @see Comparator
295 */
296 public static <T> int compare(T a, T b, Comparator<? super T> c) {
297 return (a == b) ? 0 : c.compare(a, b);
298 }
299
300 /**
301 * Checks that the specified object reference is not {@code null}. This
302 * method is designed primarily for doing parameter validation in methods
303 * and constructors, as demonstrated below:
304 * <blockquote><pre>
305 * public Foo(Bar bar) {
306 * this.bar = Objects.requireNonNull(bar);
307 * }
308 * </pre></blockquote>
309 *
310 * @param obj the object reference to check for nullity
311 * @param <T> the type of the reference
312 * @return {@code obj} if not {@code null}
313 * @throws NullPointerException if {@code obj} is {@code null}
314 */
315 @ForceInline
316 public static <T> T requireNonNull(T obj) {
317 if (obj == null)
318 throw new NullPointerException();
319 return obj;
320 }
321
322 /**
323 * Checks that the specified object reference is not {@code null} and
324 * throws a customized {@link NullPointerException} if it is. This method
325 * is designed primarily for doing parameter validation in methods and
326 * constructors with multiple parameters, as demonstrated below:
327 * <blockquote><pre>
328 * public Foo(Bar bar, Baz baz) {
329 * this.bar = Objects.requireNonNull(bar, "bar must not be null");
330 * this.baz = Objects.requireNonNull(baz, "baz must not be null");
331 * }
332 * </pre></blockquote>
333 *
334 * @param obj the object reference to check for nullity
335 * @param message detail message to be used in the event that a {@code
336 * NullPointerException} is thrown
337 * @param <T> the type of the reference
338 * @return {@code obj} if not {@code null}
339 * @throws NullPointerException if {@code obj} is {@code null}
340 */
341 @ForceInline
342 public static <T> T requireNonNull(T obj, String message) {
343 if (obj == null)
344 throw new NullPointerException(message);
345 return obj;
346 }
347
348 /**
349 * {@return {@code true} if the provided reference is {@code
350 * null}; {@code false} otherwise}
351 *
352 * @apiNote This method exists to be used as a
353 * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
354 *
355 * @param obj a reference to be checked against {@code null}
356 *
357 * @see java.util.function.Predicate
358 * @since 1.8
359 */
360 public static boolean isNull(Object obj) {
361 return obj == null;
362 }
363
364 /**
365 * {@return {@code true} if the provided reference is non-{@code null};
366 * {@code false} otherwise}
367 *
368 * @apiNote This method exists to be used as a
369 * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)}
370 *
371 * @param obj a reference to be checked against {@code null}
372 *
373 * @see java.util.function.Predicate
374 * @since 1.8
375 */
376 public static boolean nonNull(Object obj) {
377 return obj != null;
378 }
379
380 /**
381 * {@return the first argument if it is non-{@code null} and
382 * otherwise the second argument if it is non-{@code null}}
383 *
384 * @param obj an object
385 * @param defaultObj a non-{@code null} object to return if the first argument
386 * is {@code null}
387 * @param <T> the type of the reference
388 * @throws NullPointerException if both {@code obj} is null and
389 * {@code defaultObj} is {@code null}
390 * @since 9
391 */
392 public static <T> T requireNonNullElse(T obj, T defaultObj) {
393 return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
394 }
395
396 /**
397 * {@return the first argument if it is non-{@code null} and
398 * otherwise the value from {@code supplier.get()} if it is
399 * non-{@code null}}
400 *
401 * @param obj an object
402 * @param supplier of a non-{@code null} object to return if the first argument
403 * is {@code null}
404 * @param <T> the type of the first argument and return type
405 * @throws NullPointerException if both {@code obj} is null and
406 * either the {@code supplier} is {@code null} or
407 * the {@code supplier.get()} value is {@code null}
408 * @since 9
409 */
410 public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) {
411 return (obj != null) ? obj
412 : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()");
413 }
414
415 /**
416 * Checks that the specified object reference is not {@code null} and
417 * throws a customized {@link NullPointerException} if it is.
418 *
419 * <p>Unlike the method {@link #requireNonNull(Object, String)},
420 * this method allows creation of the message to be deferred until
421 * after the null check is made. While this may confer a
422 * performance advantage in the non-null case, when deciding to
423 * call this method care should be taken that the costs of
424 * creating the message supplier are less than the cost of just
425 * creating the string message directly.
426 *
427 * @param obj the object reference to check for nullity
428 * @param messageSupplier supplier of the detail message to be
429 * used in the event that a {@code NullPointerException} is thrown
430 * @param <T> the type of the reference
431 * @return {@code obj} if not {@code null}
432 * @throws NullPointerException if {@code obj} is {@code null}
433 * @since 1.8
434 */
435 public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
436 if (obj == null)
437 throw new NullPointerException(messageSupplier == null ?
438 null : messageSupplier.get());
439 return obj;
440 }
441
442 /**
443 * Checks if the {@code index} is within the bounds of the range from
444 * {@code 0} (inclusive) to {@code length} (exclusive).
445 *
446 * <p>The {@code index} is defined to be out of bounds if any of the
447 * following inequalities is true:
448 * <ul>
449 * <li>{@code index < 0}</li>
450 * <li>{@code index >= length}</li>
451 * <li>{@code length < 0}, which is implied from the former inequalities</li>
452 * </ul>
453 *
454 * @param index the index
455 * @param length the upper-bound (exclusive) of the range
456 * @return {@code index} if it is within bounds of the range
457 * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
458 * @since 9
459 */
460 @ForceInline
461 public static
462 int checkIndex(int index, int length) {
463 return Preconditions.checkIndex(index, length, null);
464 }
465
466 /**
467 * Checks if the sub-range from {@code fromIndex} (inclusive) to
468 * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
469 * (inclusive) to {@code length} (exclusive).
470 *
471 * <p>The sub-range is defined to be out of bounds if any of the following
472 * inequalities is true:
473 * <ul>
474 * <li>{@code fromIndex < 0}</li>
475 * <li>{@code fromIndex > toIndex}</li>
476 * <li>{@code toIndex > length}</li>
477 * <li>{@code length < 0}, which is implied from the former inequalities</li>
478 * </ul>
479 *
480 * @param fromIndex the lower-bound (inclusive) of the sub-range
481 * @param toIndex the upper-bound (exclusive) of the sub-range
482 * @param length the upper-bound (exclusive) the range
483 * @return {@code fromIndex} if the sub-range within bounds of the range
484 * @throws IndexOutOfBoundsException if the sub-range is out of bounds
485 * @since 9
486 */
487 public static
488 int checkFromToIndex(int fromIndex, int toIndex, int length) {
489 return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
490 }
491
492 /**
493 * Checks if the sub-range from {@code fromIndex} (inclusive) to
494 * {@code fromIndex + size} (exclusive) is within the bounds of range from
495 * {@code 0} (inclusive) to {@code length} (exclusive).
496 *
497 * <p>The sub-range is defined to be out of bounds if any of the following
498 * inequalities is true:
499 * <ul>
500 * <li>{@code fromIndex < 0}</li>
501 * <li>{@code size < 0}</li>
502 * <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
503 * <li>{@code length < 0}, which is implied from the former inequalities</li>
504 * </ul>
505 *
506 * @param fromIndex the lower-bound (inclusive) of the sub-interval
507 * @param size the size of the sub-range
508 * @param length the upper-bound (exclusive) of the range
509 * @return {@code fromIndex} if the sub-range within bounds of the range
510 * @throws IndexOutOfBoundsException if the sub-range is out of bounds
511 * @since 9
512 */
513 public static
514 int checkFromIndexSize(int fromIndex, int size, int length) {
515 return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
516 }
517
518 /**
519 * Checks if the {@code index} is within the bounds of the range from
520 * {@code 0} (inclusive) to {@code length} (exclusive).
521 *
522 * <p>The {@code index} is defined to be out of bounds if any of the
523 * following inequalities is true:
524 * <ul>
525 * <li>{@code index < 0}</li>
526 * <li>{@code index >= length}</li>
527 * <li>{@code length < 0}, which is implied from the former inequalities</li>
528 * </ul>
529 *
530 * @param index the index
531 * @param length the upper-bound (exclusive) of the range
532 * @return {@code index} if it is within bounds of the range
533 * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
534 * @since 16
535 */
536 @ForceInline
537 public static
538 long checkIndex(long index, long length) {
539 return Preconditions.checkIndex(index, length, null);
540 }
541
542 /**
543 * Checks if the sub-range from {@code fromIndex} (inclusive) to
544 * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
545 * (inclusive) to {@code length} (exclusive).
546 *
547 * <p>The sub-range is defined to be out of bounds if any of the following
548 * inequalities is true:
549 * <ul>
550 * <li>{@code fromIndex < 0}</li>
551 * <li>{@code fromIndex > toIndex}</li>
552 * <li>{@code toIndex > length}</li>
553 * <li>{@code length < 0}, which is implied from the former inequalities</li>
554 * </ul>
555 *
556 * @param fromIndex the lower-bound (inclusive) of the sub-range
557 * @param toIndex the upper-bound (exclusive) of the sub-range
558 * @param length the upper-bound (exclusive) the range
559 * @return {@code fromIndex} if the sub-range within bounds of the range
560 * @throws IndexOutOfBoundsException if the sub-range is out of bounds
561 * @since 16
562 */
563 public static
564 long checkFromToIndex(long fromIndex, long toIndex, long length) {
565 return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
566 }
567
568 /**
569 * Checks if the sub-range from {@code fromIndex} (inclusive) to
570 * {@code fromIndex + size} (exclusive) is within the bounds of range from
571 * {@code 0} (inclusive) to {@code length} (exclusive).
572 *
573 * <p>The sub-range is defined to be out of bounds if any of the following
574 * inequalities is true:
575 * <ul>
576 * <li>{@code fromIndex < 0}</li>
577 * <li>{@code size < 0}</li>
578 * <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
579 * <li>{@code length < 0}, which is implied from the former inequalities</li>
580 * </ul>
581 *
582 * @param fromIndex the lower-bound (inclusive) of the sub-interval
583 * @param size the size of the sub-range
584 * @param length the upper-bound (exclusive) of the range
585 * @return {@code fromIndex} if the sub-range within bounds of the range
586 * @throws IndexOutOfBoundsException if the sub-range is out of bounds
587 * @since 16
588 */
589 public static
590 long checkFromIndexSize(long fromIndex, long size, long length) {
591 return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
592 }
593 }