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











414     /**
415      * Checks if the {@code index} is within the bounds of the range from
416      * {@code 0} (inclusive) to {@code length} (exclusive).
417      *
418      * <p>The {@code index} is defined to be out of bounds if any of the
419      * following inequalities is true:
420      * <ul>
421      *  <li>{@code index < 0}</li>
422      *  <li>{@code index >= length}</li>
423      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
424      * </ul>
425      *
426      * @param index the index
427      * @param length the upper-bound (exclusive) of the range
428      * @return {@code index} if it is within bounds of the range
429      * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
430      * @since 16
431      */
432     @ForceInline
433     public static
434     long checkIndex(long index, long length) {
435         return Preconditions.checkIndex(index, length, null);
436     }
437 
438     /**
439      * Checks if the sub-range from {@code fromIndex} (inclusive) to
440      * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
441      * (inclusive) to {@code length} (exclusive).
442      *
443      * <p>The sub-range is defined to be out of bounds if any of the following
444      * inequalities is true:
445      * <ul>
446      *  <li>{@code fromIndex < 0}</li>
447      *  <li>{@code fromIndex > toIndex}</li>
448      *  <li>{@code toIndex > length}</li>
449      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
450      * </ul>
451      *
452      * @param fromIndex the lower-bound (inclusive) of the sub-range
453      * @param toIndex the upper-bound (exclusive) of the sub-range
454      * @param length the upper-bound (exclusive) the range
455      * @return {@code fromIndex} if the sub-range within bounds of the range
456      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
457      * @since 16
458      */
459     public static
460     long checkFromToIndex(long fromIndex, long toIndex, long length) {
461         return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
462     }
463 
464     /**
465      * Checks if the sub-range from {@code fromIndex} (inclusive) to
466      * {@code fromIndex + size} (exclusive) is within the bounds of range from
467      * {@code 0} (inclusive) to {@code length} (exclusive).
468      *
469      * <p>The sub-range is defined to be out of bounds if any of the following
470      * inequalities is true:
471      * <ul>
472      *  <li>{@code fromIndex < 0}</li>
473      *  <li>{@code size < 0}</li>
474      *  <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
475      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
476      * </ul>
477      *
478      * @param fromIndex the lower-bound (inclusive) of the sub-interval
479      * @param size the size of the sub-range
480      * @param length the upper-bound (exclusive) of the range
481      * @return {@code fromIndex} if the sub-range within bounds of the range
482      * @throws IndexOutOfBoundsException if the sub-range is out of bounds
483      * @since 16
484      */
485     public static
486     long checkFromIndexSize(long fromIndex, long size, long length) {
487         return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
488     }











489 }
--- EOF ---