1 /*
  2  * Copyright (c) 2009, 2016, 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  * @apiNote
 42  * Static methods such as {@link Objects#checkIndex},
 43  * {@link Objects#checkFromToIndex}, and {@link Objects#checkFromIndexSize} are
 44  * provided for the convenience of checking if values corresponding to indexes
 45  * and sub-ranges are out of bounds.
 46  * Variations of these static methods support customization of the runtime
 47  * exception, and corresponding exception detail message, that is thrown when
 48  * values are out of bounds.  Such methods accept a functional interface
 49  * argument, instances of {@code BiFunction}, that maps out-of-bound values to a
 50  * runtime exception.  Care should be taken when using such methods in
 51  * combination with an argument that is a lambda expression, method reference or
 52  * class that capture values.  In such cases the cost of capture, related to
 53  * functional interface allocation, may exceed the cost of checking bounds.
 54  *
 55  * @since 1.7
 56  */
 57 public final class Objects {
 58     private Objects() {
 59         throw new AssertionError("No java.util.Objects instances for you!");
 60     }
 61 
 62     /**
 63      * Returns {@code true} if the arguments are equal to each other
 64      * and {@code false} otherwise.
 65      * Consequently, if both arguments are {@code null}, {@code true}
 66      * is returned.  Otherwise, if the first argument is not {@code
 67      * null}, equality is determined by calling the {@link
 68      * Object#equals equals} method of the first argument with the
 69      * second argument of this method. Otherwise, {@code false} is
 70      * returned.
 71      *
 72      * @param a an object
 73      * @param b an object to be compared with {@code a} for equality
 74      * @return {@code true} if the arguments are equal to each other
 75      * and {@code false} otherwise
 76      * @see Object#equals(Object)
 77      */
 78     public static boolean equals(Object a, Object b) {
 79         return (a == b) || (a != null && a.equals(b));
 80     }
 81 
 82    /**
 83     * Returns {@code true} if the arguments are deeply equal to each other
 84     * and {@code false} otherwise.
 85     *
 86     * Two {@code null} values are deeply equal.  If both arguments are
 87     * arrays, the algorithm in {@link Arrays#deepEquals(Object[],
 88     * Object[]) Arrays.deepEquals} is used to determine equality.
 89     * Otherwise, equality is determined by using the {@link
 90     * Object#equals equals} method of the first argument.
 91     *
 92     * @param a an object
 93     * @param b an object to be compared with {@code a} for deep equality
 94     * @return {@code true} if the arguments are deeply equal to each other
 95     * and {@code false} otherwise
 96     * @see Arrays#deepEquals(Object[], Object[])
 97     * @see Objects#equals(Object, Object)
 98     */
 99     public static boolean deepEquals(Object a, Object b) {
100         if (a == b)
101             return true;
102         else if (a == null || b == null)
103             return false;
104         else
105             return Arrays.deepEquals0(a, b);
106     }
107 
108     /**
109      * Returns the hash code of a non-{@code null} argument and 0 for
110      * a {@code null} argument.
111      *
112      * @param o an object
113      * @return the hash code of a non-{@code null} argument and 0 for
114      * a {@code null} argument
115      * @see Object#hashCode
116      */
117     public static int hashCode(Object o) {
118         return o != null ? o.hashCode() : 0;
119     }
120 
121    /**
122     * Generates a hash code for a sequence of input values. The hash
123     * code is generated as if all the input values were placed into an
124     * array, and that array were hashed by calling {@link
125     * Arrays#hashCode(Object[])}.
126     *
127     * <p>This method is useful for implementing {@link
128     * Object#hashCode()} on objects containing multiple fields. For
129     * example, if an object that has three fields, {@code x}, {@code
130     * y}, and {@code z}, one could write:
131     *
132     * <blockquote><pre>
133     * &#064;Override public int hashCode() {
134     *     return Objects.hash(x, y, z);
135     * }
136     * </pre></blockquote>
137     *
138     * <b>Warning: When a single object reference is supplied, the returned
139     * value does not equal the hash code of that object reference.</b> This
140     * value can be computed by calling {@link #hashCode(Object)}.
141     *
142     * @param values the values to be hashed
143     * @return a hash value of the sequence of input values
144     * @see Arrays#hashCode(Object[])
145     * @see List#hashCode
146     */
147     public static int hash(Object... values) {
148         return Arrays.hashCode(values);
149     }
150 
151     /**
152      * Returns the result of calling {@code toString} for a non-{@code
153      * null} argument and {@code "null"} for a {@code null} argument.
154      *
155      * @param o an object
156      * @return the result of calling {@code toString} for a non-{@code
157      * null} argument and {@code "null"} for a {@code null} argument
158      * @see Object#toString
159      * @see String#valueOf(Object)
160      */
161     public static String toString(Object o) {
162         return String.valueOf(o);
163     }
164 
165     /**
166      * Returns the result of calling {@code toString} on the first
167      * argument if the first argument is not {@code null} and returns
168      * the second argument otherwise.
169      *
170      * @param o an object
171      * @param nullDefault string to return if the first argument is
172      *        {@code null}
173      * @return the result of calling {@code toString} on the first
174      * argument if it is not {@code null} and the second argument
175      * otherwise.
176      * @see Objects#toString(Object)
177      */
178     public static String toString(Object o, String nullDefault) {
179         return (o != null) ? o.toString() : nullDefault;
180     }
181 
182     /**
183      * Returns 0 if the arguments are identical and {@code
184      * c.compare(a, b)} otherwise.
185      * Consequently, if both arguments are {@code null} 0
186      * is returned.
187      *
188      * <p>Note that if one of the arguments is {@code null}, a {@code
189      * NullPointerException} may or may not be thrown depending on
190      * what ordering policy, if any, the {@link Comparator Comparator}
191      * chooses to have for {@code null} values.
192      *
193      * @param <T> the type of the objects being compared
194      * @param a an object
195      * @param b an object to be compared with {@code a}
196      * @param c the {@code Comparator} to compare the first two arguments
197      * @return 0 if the arguments are identical and {@code
198      * c.compare(a, b)} otherwise.
199      * @see Comparable
200      * @see Comparator
201      */
202     public static <T> int compare(T a, T b, Comparator<? super T> c) {
203         return (a == b) ? 0 :  c.compare(a, b);
204     }
205 
206     /**
207      * Checks that the specified object reference is not {@code null}. This
208      * method is designed primarily for doing parameter validation in methods
209      * and constructors, as demonstrated below:
210      * <blockquote><pre>
211      * public Foo(Bar bar) {
212      *     this.bar = Objects.requireNonNull(bar);
213      * }
214      * </pre></blockquote>
215      *
216      * @param obj the object reference to check for nullity
217      * @param <T> the type of the reference
218      * @return {@code obj} if not {@code null}
219      * @throws NullPointerException if {@code obj} is {@code null}
220      */
221     public static <T> T requireNonNull(T obj) {
222         if (obj == null)
223             throw new NullPointerException();
224         return obj;
225     }
226 
227     /**
228      * Checks that the specified object reference is not {@code null} and
229      * throws a customized {@link NullPointerException} if it is. This method
230      * is designed primarily for doing parameter validation in methods and
231      * constructors with multiple parameters, as demonstrated below:
232      * <blockquote><pre>
233      * public Foo(Bar bar, Baz baz) {
234      *     this.bar = Objects.requireNonNull(bar, "bar must not be null");
235      *     this.baz = Objects.requireNonNull(baz, "baz must not be null");
236      * }
237      * </pre></blockquote>
238      *
239      * @param obj     the object reference to check for nullity
240      * @param message detail message to be used in the event that a {@code
241      *                NullPointerException} is thrown
242      * @param <T> the type of the reference
243      * @return {@code obj} if not {@code null}
244      * @throws NullPointerException if {@code obj} is {@code null}
245      */
246     public static <T> T requireNonNull(T obj, String message) {
247         if (obj == null)
248             throw new NullPointerException(message);
249         return obj;
250     }
251 
252     /**
253      * Returns {@code true} if the provided reference is {@code null} otherwise
254      * returns {@code false}.
255      *
256      * @apiNote This method exists to be used as a
257      * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
258      *
259      * @param obj a reference to be checked against {@code null}
260      * @return {@code true} if the provided reference is {@code null} otherwise
261      * {@code false}
262      *
263      * @see java.util.function.Predicate
264      * @since 1.8
265      */
266     public static boolean isNull(Object obj) {
267         return obj == null;
268     }
269 
270     /**
271      * Returns {@code true} if the provided reference is non-{@code null}
272      * otherwise returns {@code false}.
273      *
274      * @apiNote This method exists to be used as a
275      * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)}
276      *
277      * @param obj a reference to be checked against {@code null}
278      * @return {@code true} if the provided reference is non-{@code null}
279      * otherwise {@code false}
280      *
281      * @see java.util.function.Predicate
282      * @since 1.8
283      */
284     public static boolean nonNull(Object obj) {
285         return obj != null;
286     }
287 
288     /**
289      * Returns the first argument if it is non-{@code null} and
290      * otherwise returns the non-{@code null} second argument.
291      *
292      * @param obj an object
293      * @param defaultObj a non-{@code null} object to return if the first argument
294      *                   is {@code null}
295      * @param <T> the type of the reference
296      * @return the first argument if it is non-{@code null} and
297      *        otherwise the second argument if it is non-{@code null}
298      * @throws NullPointerException if both {@code obj} is null and
299      *        {@code defaultObj} is {@code null}
300      * @since 9
301      */
302     public static <T> T requireNonNullElse(T obj, T defaultObj) {
303         return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
304     }
305 
306     /**
307      * Returns the first argument if it is non-{@code null} and otherwise
308      * returns the non-{@code null} value of {@code supplier.get()}.
309      *
310      * @param obj an object
311      * @param supplier of a non-{@code null} object to return if the first argument
312      *                 is {@code null}
313      * @param <T> the type of the first argument and return type
314      * @return the first argument if it is non-{@code null} and otherwise
315      *         the value from {@code supplier.get()} if it is non-{@code null}
316      * @throws NullPointerException if both {@code obj} is null and
317      *        either the {@code supplier} is {@code null} or
318      *        the {@code supplier.get()} value is {@code null}
319      * @since 9
320      */
321     public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) {
322         return (obj != null) ? obj
323                 : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()");
324     }
325 
326     /**
327      * Checks that the specified object reference is not {@code null} and
328      * throws a customized {@link NullPointerException} if it is.
329      *
330      * <p>Unlike the method {@link #requireNonNull(Object, String)},
331      * this method allows creation of the message to be deferred until
332      * after the null check is made. While this may confer a
333      * performance advantage in the non-null case, when deciding to
334      * call this method care should be taken that the costs of
335      * creating the message supplier are less than the cost of just
336      * creating the string message directly.
337      *
338      * @param obj     the object reference to check for nullity
339      * @param messageSupplier supplier of the detail message to be
340      * used in the event that a {@code NullPointerException} is thrown
341      * @param <T> the type of the reference
342      * @return {@code obj} if not {@code null}
343      * @throws NullPointerException if {@code obj} is {@code null}
344      * @since 1.8
345      */
346     public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
347         if (obj == null)
348             throw new NullPointerException(messageSupplier == null ?
349                                            null : messageSupplier.get());
350         return obj;
351     }
352 
353     /**
354      * Checks if the {@code index} is within the bounds of the range from
355      * {@code 0} (inclusive) to {@code length} (exclusive).
356      *
357      * <p>The {@code index} is defined to be out of bounds if any of the
358      * following inequalities is true:
359      * <ul>
360      *  <li>{@code index < 0}</li>
361      *  <li>{@code index >= length}</li>
362      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
363      * </ul>
364      *
365      * @param index the index
366      * @param length the upper-bound (exclusive) of the range
367      * @return {@code index} if it is within bounds of the range
368      * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
369      * @since 9
370      */
371     @ForceInline
372     public static
373     int checkIndex(int index, int length) {
374         return Preconditions.checkIndex(index, length, null);
375     }
376 
377     /**
378      * Checks if the sub-range from {@code fromIndex} (inclusive) to
379      * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
380      * (inclusive) to {@code length} (exclusive).
381      *
382      * <p>The sub-range is defined to be out of bounds if any of the following
383      * inequalities is true:
384      * <ul>
385      *  <li>{@code fromIndex < 0}</li>
386      *  <li>{@code fromIndex > toIndex}</li>
387      *  <li>{@code toIndex > length}</li>
388      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
389      * </ul>
390      *
391      * @param fromIndex the lower-bound (inclusive) of the sub-range
392      * @param toIndex the upper-bound (exclusive) of the sub-range
393      * @param length the upper-bound (exclusive) the range
394      * @return {@code fromIndex} if the sub-range within bounds of the range
395      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
396      * @since 9
397      */
398     public static
399     int checkFromToIndex(int fromIndex, int toIndex, int length) {
400         return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
401     }
402 
403     /**
404      * Checks if the sub-range from {@code fromIndex} (inclusive) to
405      * {@code fromIndex + size} (exclusive) is within the bounds of range from
406      * {@code 0} (inclusive) to {@code length} (exclusive).
407      *
408      * <p>The sub-range is defined to be out of bounds if any of the following
409      * inequalities is true:
410      * <ul>
411      *  <li>{@code fromIndex < 0}</li>
412      *  <li>{@code size < 0}</li>
413      *  <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
414      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
415      * </ul>
416      *
417      * @param fromIndex the lower-bound (inclusive) of the sub-interval
418      * @param size the size of the sub-range
419      * @param length the upper-bound (exclusive) of the range
420      * @return {@code fromIndex} if the sub-range within bounds of the range
421      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
422      * @since 9
423      */
424     public static
425     int checkFromIndexSize(int fromIndex, int size, int length) {
426         return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
427     }
428 
429     /**
430      * Return the size of the object in the heap.
431      *
432      * @param o an object
433      * @return the objects's size
434      * @since Valhalla
435      */
436     public static long getObjectSize(Object o) {
437         return Unsafe.getUnsafe().getObjectSize(o);
438     }
439 }