1 /* 2 * Copyright (c) 2009, 2025, 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.javac.PreviewFeature; 29 import jdk.internal.misc.PreviewFeatures; 30 import jdk.internal.util.Preconditions; 31 import jdk.internal.vm.annotation.ForceInline; 32 33 import java.util.function.Supplier; 34 35 /** 36 * This class consists of {@code static} utility methods for operating 37 * on objects, or checking certain conditions before operation. These utilities 38 * include {@code null}-safe or {@code null}-tolerant methods for computing the 39 * hash code of an object, returning a string for an object, comparing two 40 * objects, and checking if indexes or sub-range values are out of bounds. 41 * 42 * @since 1.7 43 */ 44 public final class Objects { 45 private Objects() { 46 throw new AssertionError("No java.util.Objects instances for you!"); 47 } 48 49 /** 50 * {@return {@code true} if the arguments are equal to each other 51 * and {@code false} otherwise} 52 * Consequently, if both arguments are {@code null}, {@code true} 53 * is returned. Otherwise, if the first argument is not {@code 54 * null}, equality is determined by calling the {@link 55 * Object#equals equals} method of the first argument with the 56 * second argument of this method. Otherwise, {@code false} is 57 * returned. 58 * 59 * @param a an object 60 * @param b an object to be compared with {@code a} for equality 61 * @see Object#equals(Object) 62 */ 63 @ForceInline 64 public static boolean equals(Object a, Object b) { 65 if (PreviewFeatures.isEnabled()) { 66 // With --enable-preview avoid acmp 67 return (a == null) ? b == null : a.equals(b); 68 } else { 69 return (a == b) || (a != null && a.equals(b)); 70 } 71 } 72 73 /** 74 * {@return {@code true} if the arguments are deeply equal to each other 75 * and {@code false} otherwise} 76 * 77 * Two {@code null} values are deeply equal. If both arguments are 78 * arrays, the algorithm in {@link Arrays#deepEquals(Object[], 79 * Object[]) Arrays.deepEquals} is used to determine equality. 80 * Otherwise, equality is determined by using the {@link 81 * Object#equals equals} method of the first argument. 82 * 83 * @param a an object 84 * @param b an object to be compared with {@code a} for deep equality 85 * @see Arrays#deepEquals(Object[], Object[]) 86 * @see Objects#equals(Object, Object) 87 */ 88 public static boolean deepEquals(Object a, Object b) { 89 if (a == b) 90 return true; 91 else if (a == null || b == null) 92 return false; 93 else 94 return Arrays.deepEquals0(a, b); 95 } 96 97 /** 98 * {@return the hash code of a non-{@code null} argument and 0 for 99 * a {@code null} argument} 100 * 101 * @param o an object 102 * @see Object#hashCode 103 */ 104 public static int hashCode(Object o) { 105 return o != null ? o.hashCode() : 0; 106 } 107 108 /** 109 * {@return a hash code for a sequence of input values} The hash 110 * code is generated as if all the input values were placed into an 111 * array, and that array were hashed by calling {@link 112 * Arrays#hashCode(Object[])}. 113 * 114 * <p>This method is useful for implementing {@link 115 * Object#hashCode()} on objects containing multiple fields. For 116 * example, if an object that has three fields, {@code x}, {@code 117 * y}, and {@code z}, one could write: 118 * 119 * <blockquote><pre> 120 * @Override public int hashCode() { 121 * return Objects.hash(x, y, z); 122 * } 123 * </pre></blockquote> 124 * 125 * <b>Warning: When a single object reference is supplied, the returned 126 * value does not equal the hash code of that object reference.</b> This 127 * value can be computed by calling {@link #hashCode(Object)}. 128 * 129 * @param values the values to be hashed 130 * @see Arrays#hashCode(Object[]) 131 * @see List#hashCode 132 */ 133 public static int hash(Object... values) { 134 return Arrays.hashCode(values); 135 } 136 137 /** 138 * {@return the result of calling {@code toString} for a 139 * non-{@code null} argument and {@code "null"} for a 140 * {@code null} argument} 141 * 142 * @param o an object 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 * {@return the result of calling {@code toString} on the first 152 * argument if the first argument is not {@code null} and the 153 * second argument otherwise} 154 * 155 * @param o an object 156 * @param nullDefault string to return if the first argument is 157 * {@code null} 158 * @see Objects#toString(Object) 159 */ 160 public static String toString(Object o, String nullDefault) { 161 return (o != null) ? o.toString() : nullDefault; 162 } 163 164 /** 165 * {@return a string equivalent to the string returned by {@code 166 * Object.toString} if that method and {@code hashCode} are not 167 * overridden} 168 * 169 * @implNote 170 * This method constructs a string for an object without calling 171 * any overridable methods of the object. 172 * 173 * @implSpec 174 * The method returns a string equivalent to:<br> 175 * {@code o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o))} 176 * 177 * @param o an object 178 * @throws NullPointerException if the argument is null 179 * @see Object#toString 180 * @see System#identityHashCode(Object) 181 * @since 19 182 */ 183 public static String toIdentityString(Object o) { 184 requireNonNull(o); 185 return o.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(o)); 186 } 187 188 /** 189 * {@return {@code true} if the object is a non-null reference 190 * to an {@linkplain Class#isIdentity() identity object}, otherwise {@code false}} 191 * 192 * @apiNote 193 * If the parameter is {@code null}, there is no object 194 * and hence no class to check for identity; the return is {@code false}. 195 * To test for a {@linkplain Class#isValue() value object} use: 196 * {@snippet type="java" : 197 * if (obj != null && !Objects.hasIdentity(obj)) { 198 * // obj is a non-null value object 199 * } 200 * } 201 * @param obj an object or {@code null} 202 * @since Valhalla 203 */ 204 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS) 205 // @IntrinsicCandidate 206 public static boolean hasIdentity(Object obj) { 207 return (obj == null) ? false : obj.getClass().isIdentity(); 208 } 209 210 /** 211 * {@return {@code true} if the object is a non-null reference 212 * to a {@linkplain Class#isValue() value object}, otherwise {@code false}} 213 * 214 * @param obj an object or {@code null} 215 * @since Valhalla 216 */ 217 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS) 218 // @IntrinsicCandidate 219 public static boolean isValueObject(Object obj) { 220 return (obj == null) ? false : obj.getClass().isValue(); 221 } 222 223 /** 224 * Checks that the specified object reference is an identity object. 225 * 226 * @param obj the object reference to check for identity 227 * @param <T> the type of the reference 228 * @return {@code obj} if {@code obj} is an identity object 229 * @throws NullPointerException if {@code obj} is {@code null} 230 * @throws IdentityException if {@code obj} is not an identity object 231 * @since Valhalla 232 */ 233 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS) 234 @ForceInline 235 public static <T> T requireIdentity(T obj) { 236 Objects.requireNonNull(obj); 237 if (!hasIdentity(obj)) 238 throw new IdentityException(obj.getClass()); 239 return obj; 240 } 241 242 /** 243 * Checks that the specified object reference is an identity object. 244 * 245 * @param obj the object reference to check for identity 246 * @param message detail message to be used in the event that an 247 * {@code IdentityException} is thrown; may be null 248 * @param <T> the type of the reference 249 * @return {@code obj} if {@code obj} is an identity object 250 * @throws NullPointerException if {@code obj} is {@code null} 251 * @throws IdentityException if {@code obj} is not an identity object 252 * @since Valhalla 253 */ 254 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS) 255 @ForceInline 256 public static <T> T requireIdentity(T obj, String message) { 257 Objects.requireNonNull(obj); 258 if (!hasIdentity(obj)) 259 throw new IdentityException(message); 260 return obj; 261 } 262 263 /** 264 * Checks that the specified object reference is an identity object. 265 * 266 * @param obj the object reference to check for identity 267 * @param messageSupplier supplier of the detail message to be 268 * used in the event that an {@code IdentityException} is thrown; may be null 269 * @param <T> the type of the reference 270 * @return {@code obj} if {@code obj} is an identity object 271 * @throws NullPointerException if {@code obj} is {@code null} 272 * @throws IdentityException if {@code obj} is not an identity object 273 * @since Valhalla 274 */ 275 @PreviewFeature(feature = PreviewFeature.Feature.VALUE_OBJECTS) 276 @ForceInline 277 public static <T> T requireIdentity(T obj, Supplier<String> messageSupplier) { 278 Objects.requireNonNull(obj); 279 if (!hasIdentity(obj)) 280 throw new IdentityException(messageSupplier == null ? 281 null : messageSupplier.get()); 282 return obj; 283 } 284 285 /** 286 * {@return 0 if the arguments are identical and {@code 287 * c.compare(a, b)} otherwise} 288 * Consequently, if both arguments are {@code null} 0 289 * is returned. 290 * 291 * <p>Note that if one of the arguments is {@code null}, a {@code 292 * NullPointerException} may or may not be thrown depending on 293 * what ordering policy, if any, the {@link Comparator Comparator} 294 * chooses to have for {@code null} values. 295 * 296 * @param <T> the type of the objects being compared 297 * @param a an object 298 * @param b an object to be compared with {@code a} 299 * @param c the {@code Comparator} to compare the first two arguments 300 * @see Comparable 301 * @see Comparator 302 */ 303 public static <T> int compare(T a, T b, Comparator<? super T> c) { 304 return (a == b) ? 0 : c.compare(a, b); 305 } 306 307 /** 308 * Checks that the specified object reference is not {@code null}. This 309 * method is designed primarily for doing parameter validation in methods 310 * and constructors, as demonstrated below: 311 * <blockquote><pre> 312 * public Foo(Bar bar) { 313 * this.bar = Objects.requireNonNull(bar); 314 * } 315 * </pre></blockquote> 316 * 317 * @param obj the object reference to check for nullity 318 * @param <T> the type of the reference 319 * @return {@code obj} if not {@code null} 320 * @throws NullPointerException if {@code obj} is {@code null} 321 */ 322 @ForceInline 323 public static <T> T requireNonNull(T obj) { 324 if (obj == null) 325 throw new NullPointerException(); 326 return obj; 327 } 328 329 /** 330 * Checks that the specified object reference is not {@code null} and 331 * throws a customized {@link NullPointerException} if it is. This method 332 * is designed primarily for doing parameter validation in methods and 333 * constructors with multiple parameters, as demonstrated below: 334 * <blockquote><pre> 335 * public Foo(Bar bar, Baz baz) { 336 * this.bar = Objects.requireNonNull(bar, "bar must not be null"); 337 * this.baz = Objects.requireNonNull(baz, "baz must not be null"); 338 * } 339 * </pre></blockquote> 340 * 341 * @param obj the object reference to check for nullity 342 * @param message detail message to be used in the event that a {@code 343 * NullPointerException} is thrown 344 * @param <T> the type of the reference 345 * @return {@code obj} if not {@code null} 346 * @throws NullPointerException if {@code obj} is {@code null} 347 */ 348 @ForceInline 349 public static <T> T requireNonNull(T obj, String message) { 350 if (obj == null) 351 throw new NullPointerException(message); 352 return obj; 353 } 354 355 /** 356 * {@return {@code true} if the provided reference is {@code 357 * null}; {@code false} otherwise} 358 * 359 * @apiNote This method exists to be used as a 360 * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)} 361 * 362 * @param obj a reference to be checked against {@code null} 363 * 364 * @see java.util.function.Predicate 365 * @since 1.8 366 */ 367 public static boolean isNull(Object obj) { 368 return obj == null; 369 } 370 371 /** 372 * {@return {@code true} if the provided reference is non-{@code null}; 373 * {@code false} otherwise} 374 * 375 * @apiNote This method exists to be used as a 376 * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)} 377 * 378 * @param obj a reference to be checked against {@code null} 379 * 380 * @see java.util.function.Predicate 381 * @since 1.8 382 */ 383 public static boolean nonNull(Object obj) { 384 return obj != null; 385 } 386 387 /** 388 * {@return the first argument if it is non-{@code null} and 389 * otherwise the second argument if it is non-{@code null}} 390 * 391 * @param obj an object 392 * @param defaultObj a non-{@code null} object to return if the first argument 393 * is {@code null} 394 * @param <T> the type of the reference 395 * @throws NullPointerException if both {@code obj} is null and 396 * {@code defaultObj} is {@code null} 397 * @since 9 398 */ 399 public static <T> T requireNonNullElse(T obj, T defaultObj) { 400 return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj"); 401 } 402 403 /** 404 * {@return the first argument if it is non-{@code null} and 405 * otherwise the value from {@code supplier.get()} if it is 406 * non-{@code null}} 407 * 408 * @param obj an object 409 * @param supplier of a non-{@code null} object to return if the first argument 410 * is {@code null} 411 * @param <T> the type of the first argument and return type 412 * @throws NullPointerException if both {@code obj} is null and 413 * either the {@code supplier} is {@code null} or 414 * the {@code supplier.get()} value is {@code null} 415 * @since 9 416 */ 417 public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) { 418 return (obj != null) ? obj 419 : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()"); 420 } 421 422 /** 423 * Checks that the specified object reference is not {@code null} and 424 * throws a customized {@link NullPointerException} if it is. 425 * 426 * <p>Unlike the method {@link #requireNonNull(Object, String)}, 427 * this method allows creation of the message to be deferred until 428 * after the null check is made. While this may confer a 429 * performance advantage in the non-null case, when deciding to 430 * call this method care should be taken that the costs of 431 * creating the message supplier are less than the cost of just 432 * creating the string message directly. 433 * 434 * @param obj the object reference to check for nullity 435 * @param messageSupplier supplier of the detail message to be 436 * used in the event that a {@code NullPointerException} is thrown 437 * @param <T> the type of the reference 438 * @return {@code obj} if not {@code null} 439 * @throws NullPointerException if {@code obj} is {@code null} 440 * @since 1.8 441 */ 442 public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) { 443 if (obj == null) 444 throw new NullPointerException(messageSupplier == null ? 445 null : messageSupplier.get()); 446 return obj; 447 } 448 449 /** 450 * Checks if the {@code index} is within the bounds of the range from 451 * {@code 0} (inclusive) to {@code length} (exclusive). 452 * 453 * <p>The {@code index} is defined to be out of bounds if any of the 454 * following inequalities is true: 455 * <ul> 456 * <li>{@code index < 0}</li> 457 * <li>{@code index >= length}</li> 458 * <li>{@code length < 0}, which is implied from the former inequalities</li> 459 * </ul> 460 * 461 * @param index the index 462 * @param length the upper-bound (exclusive) of the range 463 * @return {@code index} if it is within bounds of the range 464 * @throws IndexOutOfBoundsException if the {@code index} is out of bounds 465 * @since 9 466 */ 467 @ForceInline 468 public static 469 int checkIndex(int index, int length) { 470 return Preconditions.checkIndex(index, length, null); 471 } 472 473 /** 474 * Checks if the sub-range from {@code fromIndex} (inclusive) to 475 * {@code toIndex} (exclusive) is within the bounds of range from {@code 0} 476 * (inclusive) to {@code length} (exclusive). 477 * 478 * <p>The sub-range is defined to be out of bounds if any of the following 479 * inequalities is true: 480 * <ul> 481 * <li>{@code fromIndex < 0}</li> 482 * <li>{@code fromIndex > toIndex}</li> 483 * <li>{@code toIndex > length}</li> 484 * <li>{@code length < 0}, which is implied from the former inequalities</li> 485 * </ul> 486 * 487 * @param fromIndex the lower-bound (inclusive) of the sub-range 488 * @param toIndex the upper-bound (exclusive) of the sub-range 489 * @param length the upper-bound (exclusive) the range 490 * @return {@code fromIndex} if the sub-range within bounds of the range 491 * @throws IndexOutOfBoundsException if the sub-range is out of bounds 492 * @since 9 493 */ 494 public static 495 int checkFromToIndex(int fromIndex, int toIndex, int length) { 496 return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null); 497 } 498 499 /** 500 * Checks if the sub-range from {@code fromIndex} (inclusive) to 501 * {@code fromIndex + size} (exclusive) is within the bounds of range from 502 * {@code 0} (inclusive) to {@code length} (exclusive). 503 * 504 * <p>The sub-range is defined to be out of bounds if any of the following 505 * inequalities is true: 506 * <ul> 507 * <li>{@code fromIndex < 0}</li> 508 * <li>{@code size < 0}</li> 509 * <li>{@code fromIndex + size > length}, taking into account integer overflow</li> 510 * <li>{@code length < 0}, which is implied from the former inequalities</li> 511 * </ul> 512 * 513 * @param fromIndex the lower-bound (inclusive) of the sub-interval 514 * @param size the size of the sub-range 515 * @param length the upper-bound (exclusive) of the range 516 * @return {@code fromIndex} if the sub-range within bounds of the range 517 * @throws IndexOutOfBoundsException if the sub-range is out of bounds 518 * @since 9 519 */ 520 public static 521 int checkFromIndexSize(int fromIndex, int size, int length) { 522 return Preconditions.checkFromIndexSize(fromIndex, size, length, null); 523 } 524 525 /** 526 * Checks if the {@code index} is within the bounds of the range from 527 * {@code 0} (inclusive) to {@code length} (exclusive). 528 * 529 * <p>The {@code index} is defined to be out of bounds if any of the 530 * following inequalities is true: 531 * <ul> 532 * <li>{@code index < 0}</li> 533 * <li>{@code index >= length}</li> 534 * <li>{@code length < 0}, which is implied from the former inequalities</li> 535 * </ul> 536 * 537 * @param index the index 538 * @param length the upper-bound (exclusive) of the range 539 * @return {@code index} if it is within bounds of the range 540 * @throws IndexOutOfBoundsException if the {@code index} is out of bounds 541 * @since 16 542 */ 543 @ForceInline 544 public static 545 long checkIndex(long index, long length) { 546 return Preconditions.checkIndex(index, length, null); 547 } 548 549 /** 550 * Checks if the sub-range from {@code fromIndex} (inclusive) to 551 * {@code toIndex} (exclusive) is within the bounds of range from {@code 0} 552 * (inclusive) to {@code length} (exclusive). 553 * 554 * <p>The sub-range is defined to be out of bounds if any of the following 555 * inequalities is true: 556 * <ul> 557 * <li>{@code fromIndex < 0}</li> 558 * <li>{@code fromIndex > toIndex}</li> 559 * <li>{@code toIndex > length}</li> 560 * <li>{@code length < 0}, which is implied from the former inequalities</li> 561 * </ul> 562 * 563 * @param fromIndex the lower-bound (inclusive) of the sub-range 564 * @param toIndex the upper-bound (exclusive) of the sub-range 565 * @param length the upper-bound (exclusive) the range 566 * @return {@code fromIndex} if the sub-range within bounds of the range 567 * @throws IndexOutOfBoundsException if the sub-range is out of bounds 568 * @since 16 569 */ 570 public static 571 long checkFromToIndex(long fromIndex, long toIndex, long length) { 572 return Preconditions.checkFromToIndex(fromIndex, toIndex, length, null); 573 } 574 575 /** 576 * Checks if the sub-range from {@code fromIndex} (inclusive) to 577 * {@code fromIndex + size} (exclusive) is within the bounds of range from 578 * {@code 0} (inclusive) to {@code length} (exclusive). 579 * 580 * <p>The sub-range is defined to be out of bounds if any of the following 581 * inequalities is true: 582 * <ul> 583 * <li>{@code fromIndex < 0}</li> 584 * <li>{@code size < 0}</li> 585 * <li>{@code fromIndex + size > length}, taking into account integer overflow</li> 586 * <li>{@code length < 0}, which is implied from the former inequalities</li> 587 * </ul> 588 * 589 * @param fromIndex the lower-bound (inclusive) of the sub-interval 590 * @param size the size of the sub-range 591 * @param length the upper-bound (exclusive) of the range 592 * @return {@code fromIndex} if the sub-range within bounds of the range 593 * @throws IndexOutOfBoundsException if the sub-range is out of bounds 594 * @since 16 595 */ 596 public static 597 long checkFromIndexSize(long fromIndex, long size, long length) { 598 return Preconditions.checkFromIndexSize(fromIndex, size, length, null); 599 } 600 }