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