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