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