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     */
189    @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
190 //    @IntrinsicCandidate
191     public static boolean hasIdentity(Object obj) {
192         requireNonNull(obj);
193         return obj.getClass().isIdentity() ||  // Before Valhalla all classes are identity classes
194                 obj.getClass() == Object.class;
195     }
196 
197     /**
198      * Checks that the specified object reference is an identity object.
199      *
200      * @param obj the object reference to check for identity
201      * @param <T> the type of the reference
202      * @return {@code obj} if {@code obj} is an identity object
203      * @throws NullPointerException if {@code obj} is {@code null}
204      * @throws IdentityException if {@code obj} is not an identity object
205      * @since Valhalla
206      */
207     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
208     @ForceInline
209     public static <T> T requireIdentity(T obj) {
210         Objects.requireNonNull(obj);
211         if (!hasIdentity(obj))
212             throw new IdentityException(obj.getClass());
213         return obj;
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 message detail message to be used in the event that an
221      *        {@code IdentityException} is thrown; may be null
222      * @param <T> the type of the reference
223      * @return {@code obj} if {@code obj} is an identity object
224      * @throws NullPointerException if {@code obj} is {@code null}
225      * @throws IdentityException if {@code obj} is not an identity object
226      * @since Valhalla
227      */
228     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
229     @ForceInline
230     public static <T> T requireIdentity(T obj, String message) {
231         Objects.requireNonNull(obj);
232         if (!hasIdentity(obj))
233             throw new IdentityException(message);
234         return obj;
235     }
236 
237     /**
238      * Checks that the specified object reference is an identity object.
239      *
240      * @param obj the object reference to check for identity
241      * @param messageSupplier supplier of the detail message to be
242      *        used in the event that an {@code IdentityException} is thrown; may be null
243      * @param <T> the type of the reference
244      * @return {@code obj} if {@code obj} is an identity object
245      * @throws NullPointerException if {@code obj} is {@code null}
246      * @throws IdentityException if {@code obj} is not an identity object
247      * @since Valhalla
248      */
249     @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS)
250     @ForceInline
251     public static <T> T requireIdentity(T obj, Supplier<String> messageSupplier) {
252         Objects.requireNonNull(obj);
253         if (!hasIdentity(obj))
254             throw new IdentityException(messageSupplier == null ?
255                     null : messageSupplier.get());
256         return obj;
257     }
258 
259     /**
260      * {@return 0 if the arguments are identical and {@code
261      * c.compare(a, b)} otherwise}
262      * Consequently, if both arguments are {@code null} 0
263      * is returned.
264      *
265      * <p>Note that if one of the arguments is {@code null}, a {@code
266      * NullPointerException} may or may not be thrown depending on
267      * what ordering policy, if any, the {@link Comparator Comparator}
268      * chooses to have for {@code null} values.
269      *
270      * @param <T> the type of the objects being compared
271      * @param a an object
272      * @param b an object to be compared with {@code a}
273      * @param c the {@code Comparator} to compare the first two arguments
274      * @see Comparable
275      * @see Comparator
276      */
277     public static <T> int compare(T a, T b, Comparator<? super T> c) {
278         return (a == b) ? 0 :  c.compare(a, b);
279     }
280 
281     /**
282      * Checks that the specified object reference is not {@code null}. This
283      * method is designed primarily for doing parameter validation in methods
284      * and constructors, as demonstrated below:
285      * <blockquote><pre>
286      * public Foo(Bar bar) {
287      *     this.bar = Objects.requireNonNull(bar);
288      * }
289      * </pre></blockquote>
290      *
291      * @param obj the object reference to check for nullity
292      * @param <T> the type of the reference
293      * @return {@code obj} if not {@code null}
294      * @throws NullPointerException if {@code obj} is {@code null}
295      */
296     @ForceInline
297     public static <T> T requireNonNull(T obj) {
298         if (obj == null)
299             throw new NullPointerException();
300         return obj;
301     }
302 
303     /**
304      * Checks that the specified object reference is not {@code null} and
305      * throws a customized {@link NullPointerException} if it is. This method
306      * is designed primarily for doing parameter validation in methods and
307      * constructors with multiple parameters, as demonstrated below:
308      * <blockquote><pre>
309      * public Foo(Bar bar, Baz baz) {
310      *     this.bar = Objects.requireNonNull(bar, "bar must not be null");
311      *     this.baz = Objects.requireNonNull(baz, "baz must not be null");
312      * }
313      * </pre></blockquote>
314      *
315      * @param obj     the object reference to check for nullity
316      * @param message detail message to be used in the event that a {@code
317      *                NullPointerException} is thrown
318      * @param <T> the type of the reference
319      * @return {@code obj} if not {@code null}
320      * @throws NullPointerException if {@code obj} is {@code null}
321      */
322     @ForceInline
323     public static <T> T requireNonNull(T obj, String message) {
324         if (obj == null)
325             throw new NullPointerException(message);
326         return obj;
327     }
328 
329     /**
330      * {@return {@code true} if the provided reference is {@code
331      * null}; {@code false} otherwise}
332      *
333      * @apiNote This method exists to be used as a
334      * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
335      *
336      * @param obj a reference to be checked against {@code null}
337      *
338      * @see java.util.function.Predicate
339      * @since 1.8
340      */
341     public static boolean isNull(Object obj) {
342         return obj == null;
343     }
344 
345     /**
346      * {@return {@code true} if the provided reference is non-{@code null};
347      * {@code false} otherwise}
348      *
349      * @apiNote This method exists to be used as a
350      * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)}
351      *
352      * @param obj a reference to be checked against {@code null}
353      *
354      * @see java.util.function.Predicate
355      * @since 1.8
356      */
357     public static boolean nonNull(Object obj) {
358         return obj != null;
359     }
360 
361     /**
362      * {@return the first argument if it is non-{@code null} and
363      * otherwise the second argument if it is non-{@code null}}
364      *
365      * @param obj an object
366      * @param defaultObj a non-{@code null} object to return if the first argument
367      *                   is {@code null}
368      * @param <T> the type of the reference
369      * @throws NullPointerException if both {@code obj} is null and
370      *        {@code defaultObj} is {@code null}
371      * @since 9
372      */
373     public static <T> T requireNonNullElse(T obj, T defaultObj) {
374         return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
375     }
376 
377     /**
378      * {@return the first argument if it is non-{@code null} and
379      * otherwise the value from {@code supplier.get()} if it is
380      * non-{@code null}}
381      *
382      * @param obj an object
383      * @param supplier of a non-{@code null} object to return if the first argument
384      *                 is {@code null}
385      * @param <T> the type of the first argument and return type
386      * @throws NullPointerException if both {@code obj} is null and
387      *        either the {@code supplier} is {@code null} or
388      *        the {@code supplier.get()} value is {@code null}
389      * @since 9
390      */
391     public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) {
392         return (obj != null) ? obj
393                 : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()");
394     }
395 
396     /**
397      * Checks that the specified object reference is not {@code null} and
398      * throws a customized {@link NullPointerException} if it is.
399      *
400      * <p>Unlike the method {@link #requireNonNull(Object, String)},
401      * this method allows creation of the message to be deferred until
402      * after the null check is made. While this may confer a
403      * performance advantage in the non-null case, when deciding to
404      * call this method care should be taken that the costs of
405      * creating the message supplier are less than the cost of just
406      * creating the string message directly.
407      *
408      * @param obj     the object reference to check for nullity
409      * @param messageSupplier supplier of the detail message to be
410      * used in the event that a {@code NullPointerException} is thrown
411      * @param <T> the type of the reference
412      * @return {@code obj} if not {@code null}
413      * @throws NullPointerException if {@code obj} is {@code null}
414      * @since 1.8
415      */
416     public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
417         if (obj == null)
418             throw new NullPointerException(messageSupplier == null ?
419                                            null : messageSupplier.get());
420         return obj;
421     }
422 
423     /**
424      * Checks if the {@code index} is within the bounds of the range from
425      * {@code 0} (inclusive) to {@code length} (exclusive).
426      *
427      * <p>The {@code index} is defined to be out of bounds if any of the
428      * following inequalities is true:
429      * <ul>
430      *  <li>{@code index < 0}</li>
431      *  <li>{@code index >= length}</li>
432      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
433      * </ul>
434      *
435      * @param index the index
436      * @param length the upper-bound (exclusive) of the range
437      * @return {@code index} if it is within bounds of the range
438      * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
439      * @since 9
440      */
441     @ForceInline
442     public static
443     int checkIndex(int index, int length) {
444         return Preconditions.checkIndex(index, length, null);
445     }
446 
447     /**
448      * Checks if the sub-range from {@code fromIndex} (inclusive) to
449      * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
450      * (inclusive) to {@code length} (exclusive).
451      *
452      * <p>The sub-range is defined to be out of bounds if any of the following
453      * inequalities is true:
454      * <ul>
455      *  <li>{@code fromIndex < 0}</li>
456      *  <li>{@code fromIndex > toIndex}</li>
457      *  <li>{@code toIndex > length}</li>
458      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
459      * </ul>
460      *
461      * @param fromIndex the lower-bound (inclusive) of the sub-range
462      * @param toIndex the upper-bound (exclusive) of the sub-range
463      * @param length the upper-bound (exclusive) the range
464      * @return {@code fromIndex} if the sub-range within bounds of the range
465      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
466      * @since 9
467      */
468     public static
469     int checkFromToIndex(int fromIndex, int toIndex, int length) {
470         return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
471     }
472 
473     /**
474      * Checks if the sub-range from {@code fromIndex} (inclusive) to
475      * {@code fromIndex + size} (exclusive) is within the bounds of range from
476      * {@code 0} (inclusive) to {@code length} (exclusive).
477      *
478      * <p>The sub-range is defined to be out of bounds if any of the following
479      * inequalities is true:
480      * <ul>
481      *  <li>{@code fromIndex < 0}</li>
482      *  <li>{@code size < 0}</li>
483      *  <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
484      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
485      * </ul>
486      *
487      * @param fromIndex the lower-bound (inclusive) of the sub-interval
488      * @param size the size of the sub-range
489      * @param length the upper-bound (exclusive) of the range
490      * @return {@code fromIndex} if the sub-range within bounds of the range
491      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
492      * @since 9
493      */
494     public static
495     int checkFromIndexSize(int fromIndex, int size, int length) {
496         return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
497     }
498 
499     /**
500      * Return the size of the object in the heap.
501      *
502      * @param o an object
503      * @return the objects's size
504      * @since Valhalla
505      */
506     public static long getObjectSize(Object o) {
507         return Unsafe.getUnsafe().getObjectSize(o);
508     }
509 
510     /**
511      * Checks if the {@code index} is within the bounds of the range from
512      * {@code 0} (inclusive) to {@code length} (exclusive).
513      *
514      * <p>The {@code index} is defined to be out of bounds if any of the
515      * following inequalities is true:
516      * <ul>
517      *  <li>{@code index < 0}</li>
518      *  <li>{@code index >= length}</li>
519      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
520      * </ul>
521      *
522      * @param index the index
523      * @param length the upper-bound (exclusive) of the range
524      * @return {@code index} if it is within bounds of the range
525      * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
526      * @since 16
527      */
528     @ForceInline
529     public static
530     long checkIndex(long index, long length) {
531         return Preconditions.checkIndex(index, length, null);
532     }
533 
534     /**
535      * Checks if the sub-range from {@code fromIndex} (inclusive) to
536      * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
537      * (inclusive) to {@code length} (exclusive).
538      *
539      * <p>The sub-range is defined to be out of bounds if any of the following
540      * inequalities is true:
541      * <ul>
542      *  <li>{@code fromIndex < 0}</li>
543      *  <li>{@code fromIndex > toIndex}</li>
544      *  <li>{@code toIndex > length}</li>
545      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
546      * </ul>
547      *
548      * @param fromIndex the lower-bound (inclusive) of the sub-range
549      * @param toIndex the upper-bound (exclusive) of the sub-range
550      * @param length the upper-bound (exclusive) the range
551      * @return {@code fromIndex} if the sub-range within bounds of the range
552      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
553      * @since 16
554      */
555     public static
556     long checkFromToIndex(long fromIndex, long toIndex, long length) {
557         return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
558     }
559 
560     /**
561      * Checks if the sub-range from {@code fromIndex} (inclusive) to
562      * {@code fromIndex + size} (exclusive) is within the bounds of range from
563      * {@code 0} (inclusive) to {@code length} (exclusive).
564      *
565      * <p>The sub-range is defined to be out of bounds if any of the following
566      * inequalities is true:
567      * <ul>
568      *  <li>{@code fromIndex < 0}</li>
569      *  <li>{@code size < 0}</li>
570      *  <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
571      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
572      * </ul>
573      *
574      * @param fromIndex the lower-bound (inclusive) of the sub-interval
575      * @param size the size of the sub-range
576      * @param length the upper-bound (exclusive) of the range
577      * @return {@code fromIndex} if the sub-range within bounds of the range
578      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
579      * @since 16
580      */
581     public static
582     long checkFromIndexSize(long fromIndex, long size, long length) {
583         return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
584     }
585 }