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