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