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