1 /*
  2  * Copyright (c) 2009, 2020, 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      * Returns 0 if the arguments are identical and {@code
170      * c.compare(a, b)} otherwise.
171      * Consequently, if both arguments are {@code null} 0
172      * is returned.
173      *
174      * <p>Note that if one of the arguments is {@code null}, a {@code
175      * NullPointerException} may or may not be thrown depending on
176      * what ordering policy, if any, the {@link Comparator Comparator}
177      * chooses to have for {@code null} values.
178      *
179      * @param <T> the type of the objects being compared
180      * @param a an object
181      * @param b an object to be compared with {@code a}
182      * @param c the {@code Comparator} to compare the first two arguments
183      * @return 0 if the arguments are identical and {@code
184      * c.compare(a, b)} otherwise.
185      * @see Comparable
186      * @see Comparator
187      */
188     public static <T> int compare(T a, T b, Comparator<? super T> c) {
189         return (a == b) ? 0 :  c.compare(a, b);
190     }
191 
192     /**
193      * Checks that the specified object reference is not {@code null}. This
194      * method is designed primarily for doing parameter validation in methods
195      * and constructors, as demonstrated below:
196      * <blockquote><pre>
197      * public Foo(Bar bar) {
198      *     this.bar = Objects.requireNonNull(bar);
199      * }
200      * </pre></blockquote>
201      *
202      * @param obj the object reference to check for nullity
203      * @param <T> the type of the reference
204      * @return {@code obj} if not {@code null}
205      * @throws NullPointerException if {@code obj} is {@code null}
206      */
207     public static <T> T requireNonNull(T obj) {
208         if (obj == null)
209             throw new NullPointerException();
210         return obj;
211     }
212 
213     /**
214      * Checks that the specified object reference is not {@code null} and
215      * throws a customized {@link NullPointerException} if it is. This method
216      * is designed primarily for doing parameter validation in methods and
217      * constructors with multiple parameters, as demonstrated below:
218      * <blockquote><pre>
219      * public Foo(Bar bar, Baz baz) {
220      *     this.bar = Objects.requireNonNull(bar, "bar must not be null");
221      *     this.baz = Objects.requireNonNull(baz, "baz must not be null");
222      * }
223      * </pre></blockquote>
224      *
225      * @param obj     the object reference to check for nullity
226      * @param message detail message to be used in the event that a {@code
227      *                NullPointerException} is thrown
228      * @param <T> the type of the reference
229      * @return {@code obj} if not {@code null}
230      * @throws NullPointerException if {@code obj} is {@code null}
231      */
232     public static <T> T requireNonNull(T obj, String message) {
233         if (obj == null)
234             throw new NullPointerException(message);
235         return obj;
236     }
237 
238     /**
239      * Returns {@code true} if the provided reference is {@code null} otherwise
240      * returns {@code false}.
241      *
242      * @apiNote This method exists to be used as a
243      * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
244      *
245      * @param obj a reference to be checked against {@code null}
246      * @return {@code true} if the provided reference is {@code null} otherwise
247      * {@code false}
248      *
249      * @see java.util.function.Predicate
250      * @since 1.8
251      */
252     public static boolean isNull(Object obj) {
253         return obj == null;
254     }
255 
256     /**
257      * Returns {@code true} if the provided reference is non-{@code null}
258      * otherwise returns {@code false}.
259      *
260      * @apiNote This method exists to be used as a
261      * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)}
262      *
263      * @param obj a reference to be checked against {@code null}
264      * @return {@code true} if the provided reference is non-{@code null}
265      * otherwise {@code false}
266      *
267      * @see java.util.function.Predicate
268      * @since 1.8
269      */
270     public static boolean nonNull(Object obj) {
271         return obj != null;
272     }
273 
274     /**
275      * Returns the first argument if it is non-{@code null} and
276      * otherwise returns the non-{@code null} second argument.
277      *
278      * @param obj an object
279      * @param defaultObj a non-{@code null} object to return if the first argument
280      *                   is {@code null}
281      * @param <T> the type of the reference
282      * @return the first argument if it is non-{@code null} and
283      *        otherwise the second argument if it is non-{@code null}
284      * @throws NullPointerException if both {@code obj} is null and
285      *        {@code defaultObj} is {@code null}
286      * @since 9
287      */
288     public static <T> T requireNonNullElse(T obj, T defaultObj) {
289         return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
290     }
291 
292     /**
293      * Returns the first argument if it is non-{@code null} and otherwise
294      * returns the non-{@code null} value of {@code supplier.get()}.
295      *
296      * @param obj an object
297      * @param supplier of a non-{@code null} object to return if the first argument
298      *                 is {@code null}
299      * @param <T> the type of the first argument and return type
300      * @return the first argument if it is non-{@code null} and otherwise
301      *         the value from {@code supplier.get()} if it is non-{@code null}
302      * @throws NullPointerException if both {@code obj} is null and
303      *        either the {@code supplier} is {@code null} or
304      *        the {@code supplier.get()} value is {@code null}
305      * @since 9
306      */
307     public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) {
308         return (obj != null) ? obj
309                 : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()");
310     }
311 
312     /**
313      * Checks that the specified object reference is not {@code null} and
314      * throws a customized {@link NullPointerException} if it is.
315      *
316      * <p>Unlike the method {@link #requireNonNull(Object, String)},
317      * this method allows creation of the message to be deferred until
318      * after the null check is made. While this may confer a
319      * performance advantage in the non-null case, when deciding to
320      * call this method care should be taken that the costs of
321      * creating the message supplier are less than the cost of just
322      * creating the string message directly.
323      *
324      * @param obj     the object reference to check for nullity
325      * @param messageSupplier supplier of the detail message to be
326      * used in the event that a {@code NullPointerException} is thrown
327      * @param <T> the type of the reference
328      * @return {@code obj} if not {@code null}
329      * @throws NullPointerException if {@code obj} is {@code null}
330      * @since 1.8
331      */
332     public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
333         if (obj == null)
334             throw new NullPointerException(messageSupplier == null ?
335                                            null : messageSupplier.get());
336         return obj;
337     }
338 
339     /**
340      * Checks if the {@code index} is within the bounds of the range from
341      * {@code 0} (inclusive) to {@code length} (exclusive).
342      *
343      * <p>The {@code index} is defined to be out of bounds if any of the
344      * following inequalities is true:
345      * <ul>
346      *  <li>{@code index < 0}</li>
347      *  <li>{@code index >= length}</li>
348      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
349      * </ul>
350      *
351      * @param index the index
352      * @param length the upper-bound (exclusive) of the range
353      * @return {@code index} if it is within bounds of the range
354      * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
355      * @since 9
356      */
357     @ForceInline
358     public static
359     int checkIndex(int index, int length) {
360         return Preconditions.checkIndex(index, length, null);
361     }
362 
363     /**
364      * Checks if the sub-range from {@code fromIndex} (inclusive) to
365      * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
366      * (inclusive) to {@code length} (exclusive).
367      *
368      * <p>The sub-range is defined to be out of bounds if any of the following
369      * inequalities is true:
370      * <ul>
371      *  <li>{@code fromIndex < 0}</li>
372      *  <li>{@code fromIndex > toIndex}</li>
373      *  <li>{@code toIndex > length}</li>
374      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
375      * </ul>
376      *
377      * @param fromIndex the lower-bound (inclusive) of the sub-range
378      * @param toIndex the upper-bound (exclusive) of the sub-range
379      * @param length the upper-bound (exclusive) the range
380      * @return {@code fromIndex} if the sub-range within bounds of the range
381      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
382      * @since 9
383      */
384     public static
385     int checkFromToIndex(int fromIndex, int toIndex, int length) {
386         return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
387     }
388 
389     /**
390      * Checks if the sub-range from {@code fromIndex} (inclusive) to
391      * {@code fromIndex + size} (exclusive) is within the bounds of range from
392      * {@code 0} (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 size < 0}</li>
399      *  <li>{@code fromIndex + size > length}, taking into account integer overflow</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-interval
404      * @param size the size of the sub-range
405      * @param length the upper-bound (exclusive) of 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 checkFromIndexSize(int fromIndex, int size, int length) {
412         return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
413     }
414 
415     /**
416      * Return the size of the object in the heap.
417      *
418      * @param o an object
419      * @return the objects's size
420      * @since Valhalla
421      */
422     public static long getObjectSize(Object o) {
423         return Unsafe.getUnsafe().getObjectSize(o);
424     }
425 
426     /**
427      * Checks if the {@code index} is within the bounds of the range from
428      * {@code 0} (inclusive) to {@code length} (exclusive).
429      *
430      * <p>The {@code index} is defined to be out of bounds if any of the
431      * following inequalities is true:
432      * <ul>
433      *  <li>{@code index < 0}</li>
434      *  <li>{@code index >= length}</li>
435      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
436      * </ul>
437      *
438      * @param index the index
439      * @param length the upper-bound (exclusive) of the range
440      * @return {@code index} if it is within bounds of the range
441      * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
442      * @since 16
443      */
444     @ForceInline
445     public static
446     long checkIndex(long index, long length) {
447         return Preconditions.checkIndex(index, length, null);
448     }
449 
450     /**
451      * Checks if the sub-range from {@code fromIndex} (inclusive) to
452      * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
453      * (inclusive) to {@code length} (exclusive).
454      *
455      * <p>The sub-range is defined to be out of bounds if any of the following
456      * inequalities is true:
457      * <ul>
458      *  <li>{@code fromIndex < 0}</li>
459      *  <li>{@code fromIndex > toIndex}</li>
460      *  <li>{@code toIndex > length}</li>
461      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
462      * </ul>
463      *
464      * @param fromIndex the lower-bound (inclusive) of the sub-range
465      * @param toIndex the upper-bound (exclusive) of the sub-range
466      * @param length the upper-bound (exclusive) the range
467      * @return {@code fromIndex} if the sub-range within bounds of the range
468      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
469      * @since 16
470      */
471     public static
472     long checkFromToIndex(long fromIndex, long toIndex, long length) {
473         return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
474     }
475 
476     /**
477      * Checks if the sub-range from {@code fromIndex} (inclusive) to
478      * {@code fromIndex + size} (exclusive) is within the bounds of range from
479      * {@code 0} (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 size < 0}</li>
486      *  <li>{@code fromIndex + size > length}, taking into account integer overflow</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-interval
491      * @param size the size of the sub-range
492      * @param length the upper-bound (exclusive) of 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 checkFromIndexSize(long fromIndex, long size, long length) {
499         return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
500     }
501     /**
502      * {@return a new instance of an unspecified class}
503      * The object has a unique identity; no other references to it exist.
504      * It can be used for synchronization, or where a placeholder Object is needed.
505      * Use this method to avoid relying on the {@linkplain Object#Object() Object constructor}.
506      *
507      * @since 17
508      */
509     public static Object newIdentity() {
510         return new Object() {};
511     }
512 }
--- EOF ---