1 /*
2 * Copyright (c) 2009, 2023, 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 * {@return {@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 * @see Object#equals(Object)
60 */
61 public static boolean equals(Object a, Object b) {
62 return (a == b) || (a != null && a.equals(b));
63 }
64
65 /**
66 * {@return {@code true} if the arguments are deeply equal to each other
67 * and {@code false} otherwise}
68 *
69 * Two {@code null} values are deeply equal. If both arguments are
70 * arrays, the algorithm in {@link Arrays#deepEquals(Object[],
71 * Object[]) Arrays.deepEquals} is used to determine equality.
72 * Otherwise, equality is determined by using the {@link
73 * Object#equals equals} method of the first argument.
74 *
75 * @param a an object
76 * @param b an object to be compared with {@code a} for deep equality
77 * @see Arrays#deepEquals(Object[], Object[])
78 * @see Objects#equals(Object, Object)
79 */
80 public static boolean deepEquals(Object a, Object b) {
81 if (a == b)
82 return true;
83 else if (a == null || b == null)
84 return false;
85 else
86 return Arrays.deepEquals0(a, b);
87 }
88
89 /**
90 * {@return the hash code of a non-{@code null} argument and 0 for
91 * a {@code null} argument}
92 *
93 * @param o an object
94 * @see Object#hashCode
95 */
96 public static int hashCode(Object o) {
97 return o != null ? o.hashCode() : 0;
98 }
99
100 /**
101 * {@return a hash code for a sequence of input values} The hash
102 * code is generated as if all the input values were placed into an
103 * array, and that array were hashed by calling {@link
104 * Arrays#hashCode(Object[])}.
105 *
106 * <p>This method is useful for implementing {@link
107 * Object#hashCode()} on objects containing multiple fields. For
108 * example, if an object that has three fields, {@code x}, {@code
109 * y}, and {@code z}, one could write:
110 *
111 * <blockquote><pre>
112 * @Override public int hashCode() {
113 * return Objects.hash(x, y, z);
114 * }
115 * </pre></blockquote>
116 *
117 * <b>Warning: When a single object reference is supplied, the returned
118 * value does not equal the hash code of that object reference.</b> This
119 * value can be computed by calling {@link #hashCode(Object)}.
120 *
121 * @param values the values to be hashed
122 * @see Arrays#hashCode(Object[])
123 * @see List#hashCode
124 */
125 public static int hash(Object... values) {
126 return Arrays.hashCode(values);
127 }
128
129 /**
130 * {@return the result of calling {@code toString} for a
131 * non-{@code null} argument and {@code "null"} for a
132 * {@code null} argument}
133 *
134 * @param o an object
135 * @see Object#toString
136 * @see String#valueOf(Object)
137 */
138 public static String toString(Object o) {
139 return String.valueOf(o);
140 }
141
142 /**
143 * {@return the result of calling {@code toString} on the first
144 * argument if the first argument is not {@code null} and the
145 * second argument otherwise}
146 *
147 * @param o an object
148 * @param nullDefault string to return if the first argument is
149 * {@code null}
150 * @see Objects#toString(Object)
151 */
152 public static String toString(Object o, String nullDefault) {
153 return (o != null) ? o.toString() : nullDefault;
154 }
155
156 /**
157 * {@return a string equivalent to the string returned by {@code
158 * Object.toString} if that method and {@code hashCode} are not
159 * overridden}
160 *
161 * @implNote
162 * This method constructs a string for an object without calling
163 * any overridable methods of the object.
164 *
165 * @implSpec
166 * The method returns a string equivalent to:<br>
167 * {@code o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o))}
168 *
169 * @param o an object
170 * @throws NullPointerException if the argument is null
171 * @see Object#toString
172 * @see System#identityHashCode(Object)
173 * @since 19
174 */
175 public static String toIdentityString(Object o) {
176 requireNonNull(o);
177 return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o));
178 }
179
180 /**
181 * {@return 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 * @see Comparable
196 * @see Comparator
197 */
198 public static <T> int compare(T a, T b, Comparator<? super T> c) {
199 return (a == b) ? 0 : c.compare(a, b);
200 }
201
202 /**
203 * Checks that the specified object reference is not {@code null}. This
204 * method is designed primarily for doing parameter validation in methods
205 * and constructors, as demonstrated below:
206 * <blockquote><pre>
207 * public Foo(Bar bar) {
208 * this.bar = Objects.requireNonNull(bar);
209 * }
210 * </pre></blockquote>
211 *
212 * @param obj the object reference to check for nullity
213 * @param <T> the type of the reference
214 * @return {@code obj} if not {@code null}
215 * @throws NullPointerException if {@code obj} is {@code null}
216 */
217 @ForceInline
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 */
243 @ForceInline
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 * {@return {@code true} if the provided reference is {@code
252 * null}; {@code false} otherwise}
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 *
259 * @see java.util.function.Predicate
260 * @since 1.8
261 */
262 public static boolean isNull(Object obj) {
263 return obj == null;
264 }
265
266 /**
267 * {@return {@code true} if the provided reference is non-{@code null};
268 * {@code false} otherwise}
269 *
270 * @apiNote This method exists to be used as a
271 * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)}
272 *
273 * @param obj a reference to be checked against {@code null}
274 *
275 * @see java.util.function.Predicate
276 * @since 1.8
277 */
278 public static boolean nonNull(Object obj) {
279 return obj != null;
280 }
281
282 /**
283 * {@return the first argument if it is non-{@code null} and
284 * otherwise the second argument if it is non-{@code null}}
285 *
286 * @param obj an object
287 * @param defaultObj a non-{@code null} object to return if the first argument
288 * is {@code null}
289 * @param <T> the type of the reference
290 * @throws NullPointerException if both {@code obj} is null and
291 * {@code defaultObj} is {@code null}
292 * @since 9
293 */
294 public static <T> T requireNonNullElse(T obj, T defaultObj) {
295 return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
296 }
297
298 /**
299 * {@return the first argument if it is non-{@code null} and
300 * otherwise the value from {@code supplier.get()} if it is
301 * non-{@code null}}
302 *
303 * @param obj an object
304 * @param supplier of a non-{@code null} object to return if the first argument
305 * is {@code null}
306 * @param <T> the type of the first argument and return type
307 * @throws NullPointerException if both {@code obj} is null and
308 * either the {@code supplier} is {@code null} or
309 * the {@code supplier.get()} value is {@code null}
310 * @since 9
311 */
312 public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) {
313 return (obj != null) ? obj
314 : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()");
315 }
316
317 /**
318 * Checks that the specified object reference is not {@code null} and
319 * throws a customized {@link NullPointerException} if it is.
320 *
321 * <p>Unlike the method {@link #requireNonNull(Object, String)},
322 * this method allows creation of the message to be deferred until
323 * after the null check is made. While this may confer a
324 * performance advantage in the non-null case, when deciding to
325 * call this method care should be taken that the costs of
326 * creating the message supplier are less than the cost of just
327 * creating the string message directly.
328 *
329 * @param obj the object reference to check for nullity
330 * @param messageSupplier supplier of the detail message to be
331 * used in the event that a {@code NullPointerException} is thrown
332 * @param <T> the type of the reference
333 * @return {@code obj} if not {@code null}
334 * @throws NullPointerException if {@code obj} is {@code null}
335 * @since 1.8
336 */
337 public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
338 if (obj == null)
339 throw new NullPointerException(messageSupplier == null ?
340 null : messageSupplier.get());
341 return obj;
342 }
343
344 /**
345 * Checks if the {@code index} is within the bounds of the range from
346 * {@code 0} (inclusive) to {@code length} (exclusive).
347 *
348 * <p>The {@code index} is defined to be out of bounds if any of the
349 * following inequalities is true:
350 * <ul>
351 * <li>{@code index < 0}</li>
352 * <li>{@code index >= length}</li>
353 * <li>{@code length < 0}, which is implied from the former inequalities</li>
354 * </ul>
355 *
356 * @param index the index
357 * @param length the upper-bound (exclusive) of the range
358 * @return {@code index} if it is within bounds of the range
359 * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
360 * @since 9
361 */
362 @ForceInline
363 public static
364 int checkIndex(int index, int length) {
365 return Preconditions.checkIndex(index, length, null);
366 }
367
368 /**
369 * Checks if the sub-range from {@code fromIndex} (inclusive) to
370 * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
371 * (inclusive) to {@code length} (exclusive).
372 *
373 * <p>The sub-range is defined to be out of bounds if any of the following
374 * inequalities is true:
375 * <ul>
376 * <li>{@code fromIndex < 0}</li>
377 * <li>{@code fromIndex > toIndex}</li>
378 * <li>{@code toIndex > length}</li>
379 * <li>{@code length < 0}, which is implied from the former inequalities</li>
380 * </ul>
381 *
382 * @param fromIndex the lower-bound (inclusive) of the sub-range
383 * @param toIndex the upper-bound (exclusive) of the sub-range
384 * @param length the upper-bound (exclusive) the range
385 * @return {@code fromIndex} if the sub-range within bounds of the range
386 * @throws IndexOutOfBoundsException if the sub-range is out of bounds
387 * @since 9
388 */
389 public static
390 int checkFromToIndex(int fromIndex, int toIndex, int length) {
391 return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
392 }
393
394 /**
395 * Checks if the sub-range from {@code fromIndex} (inclusive) to
396 * {@code fromIndex + size} (exclusive) is within the bounds of range from
397 * {@code 0} (inclusive) to {@code length} (exclusive).
398 *
399 * <p>The sub-range is defined to be out of bounds if any of the following
400 * inequalities is true:
401 * <ul>
402 * <li>{@code fromIndex < 0}</li>
403 * <li>{@code size < 0}</li>
404 * <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
405 * <li>{@code length < 0}, which is implied from the former inequalities</li>
406 * </ul>
407 *
408 * @param fromIndex the lower-bound (inclusive) of the sub-interval
409 * @param size the size of the sub-range
410 * @param length the upper-bound (exclusive) of the range
411 * @return {@code fromIndex} if the sub-range within bounds of the range
412 * @throws IndexOutOfBoundsException if the sub-range is out of bounds
413 * @since 9
414 */
415 public static
416 int checkFromIndexSize(int fromIndex, int size, int length) {
417 return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
418 }
419
420 /**
421 * Checks if the {@code index} is within the bounds of the range from
422 * {@code 0} (inclusive) to {@code length} (exclusive).
423 *
424 * <p>The {@code index} is defined to be out of bounds if any of the
425 * following inequalities is true:
426 * <ul>
427 * <li>{@code index < 0}</li>
428 * <li>{@code index >= length}</li>
429 * <li>{@code length < 0}, which is implied from the former inequalities</li>
430 * </ul>
431 *
432 * @param index the index
433 * @param length the upper-bound (exclusive) of the range
434 * @return {@code index} if it is within bounds of the range
435 * @throws IndexOutOfBoundsException if the {@code index} is out of bounds
436 * @since 16
437 */
438 @ForceInline
439 public static
440 long checkIndex(long index, long length) {
441 return Preconditions.checkIndex(index, length, null);
442 }
443
444 /**
445 * Checks if the sub-range from {@code fromIndex} (inclusive) to
446 * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
447 * (inclusive) to {@code length} (exclusive).
448 *
449 * <p>The sub-range is defined to be out of bounds if any of the following
450 * inequalities is true:
451 * <ul>
452 * <li>{@code fromIndex < 0}</li>
453 * <li>{@code fromIndex > toIndex}</li>
454 * <li>{@code toIndex > length}</li>
455 * <li>{@code length < 0}, which is implied from the former inequalities</li>
456 * </ul>
457 *
458 * @param fromIndex the lower-bound (inclusive) of the sub-range
459 * @param toIndex the upper-bound (exclusive) of the sub-range
460 * @param length the upper-bound (exclusive) the range
461 * @return {@code fromIndex} if the sub-range within bounds of the range
462 * @throws IndexOutOfBoundsException if the sub-range is out of bounds
463 * @since 16
464 */
465 public static
466 long checkFromToIndex(long fromIndex, long toIndex, long length) {
467 return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null);
468 }
469
470 /**
471 * Checks if the sub-range from {@code fromIndex} (inclusive) to
472 * {@code fromIndex + size} (exclusive) is within the bounds of range from
473 * {@code 0} (inclusive) to {@code length} (exclusive).
474 *
475 * <p>The sub-range is defined to be out of bounds if any of the following
476 * inequalities is true:
477 * <ul>
478 * <li>{@code fromIndex < 0}</li>
479 * <li>{@code size < 0}</li>
480 * <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
481 * <li>{@code length < 0}, which is implied from the former inequalities</li>
482 * </ul>
483 *
484 * @param fromIndex the lower-bound (inclusive) of the sub-interval
485 * @param size the size of the sub-range
486 * @param length the upper-bound (exclusive) of the range
487 * @return {@code fromIndex} if the sub-range within bounds of the range
488 * @throws IndexOutOfBoundsException if the sub-range is out of bounds
489 * @since 16
490 */
491 public static
492 long checkFromIndexSize(long fromIndex, long size, long length) {
493 return Preconditions.checkFromIndexSize(fromIndex, size, length, null);
494 }
495 }