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