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