1 /*
   2  * Copyright (c) 2009, 2015, 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.HotSpotIntrinsicCandidate;
  29 
  30 import java.util.function.BiFunction;
  31 import java.util.function.Function;
  32 import java.util.function.Supplier;
  33 
  34 /**
  35  * This class consists of {@code static} utility methods for operating
  36  * on objects, or checking certain conditions before operation.  These utilities
  37  * include {@code null}-safe or {@code null}-tolerant methods for computing the
  38  * hash code of an object, returning a string for an object, comparing two
  39  * objects, and checking if indexes or sub-range values are out-of-bounds.
  40  *
  41  * @apiNote
  42  * Static methods such as {@link Objects#checkIndex},
  43  * {@link Objects#checkFromToIndex}, and {@link Objects#checkFromIndexSize} are
  44  * provided for the convenience of checking if values corresponding to indexes
  45  * and sub-ranges are out-of-bounds.
  46  * Variations of these static methods support customization of the runtime
  47  * exception, and corresponding exception detail message, that is thrown when
  48  * values are out-of-bounds.  Such methods accept a functional interface
  49  * argument, instances of {@code BiFunction}, that maps out-of-bound values to a
  50  * runtime exception.  Care should be taken when using such methods in
  51  * combination with an argument that is a lambda expression, method reference or
  52  * class that capture values.  In such cases the cost of capture, related to
  53  * functional interface allocation, may exceed the cost of checking bounds.
  54  *
  55  * @since 1.7
  56  */
  57 public final class Objects {
  58     private Objects() {
  59         throw new AssertionError("No java.util.Objects instances for you!");
  60     }
  61 
  62     /**
  63      * Returns {@code true} if the arguments are equal to each other
  64      * and {@code false} otherwise.
  65      * Consequently, if both arguments are {@code null}, {@code true}
  66      * is returned and if exactly one argument is {@code null}, {@code
  67      * false} is returned.  Otherwise, equality is determined by using
  68      * the {@link Object#equals equals} method of the first
  69      * argument.
  70      *
  71      * @param a an object
  72      * @param b an object to be compared with {@code a} for equality
  73      * @return {@code true} if the arguments are equal to each other
  74      * and {@code false} otherwise
  75      * @see Object#equals(Object)
  76      */
  77     public static boolean equals(Object a, Object b) {
  78         return (a == b) || (a != null && a.equals(b));
  79     }
  80 
  81    /**
  82     * Returns {@code true} if the arguments are deeply equal to each other
  83     * and {@code false} otherwise.
  84     *
  85     * Two {@code null} values are deeply equal.  If both arguments are
  86     * arrays, the algorithm in {@link Arrays#deepEquals(Object[],
  87     * Object[]) Arrays.deepEquals} is used to determine equality.
  88     * Otherwise, equality is determined by using the {@link
  89     * Object#equals equals} method of the first argument.
  90     *
  91     * @param a an object
  92     * @param b an object to be compared with {@code a} for deep equality
  93     * @return {@code true} if the arguments are deeply equal to each other
  94     * and {@code false} otherwise
  95     * @see Arrays#deepEquals(Object[], Object[])
  96     * @see Objects#equals(Object, Object)
  97     */
  98     public static boolean deepEquals(Object a, Object b) {
  99         if (a == b)
 100             return true;
 101         else if (a == null || b == null)
 102             return false;
 103         else
 104             return Arrays.deepEquals0(a, b);
 105     }
 106 
 107     /**
 108      * Returns the hash code of a non-{@code null} argument and 0 for
 109      * a {@code null} argument.
 110      *
 111      * @param o an object
 112      * @return the hash code of a non-{@code null} argument and 0 for
 113      * a {@code null} argument
 114      * @see Object#hashCode
 115      */
 116     public static int hashCode(Object o) {
 117         return o != null ? o.hashCode() : 0;
 118     }
 119 
 120    /**
 121     * Generates a hash code for a sequence of input values. The hash
 122     * code is generated as if all the input values were placed into an
 123     * array, and that array were hashed by calling {@link
 124     * Arrays#hashCode(Object[])}.
 125     *
 126     * <p>This method is useful for implementing {@link
 127     * Object#hashCode()} on objects containing multiple fields. For
 128     * example, if an object that has three fields, {@code x}, {@code
 129     * y}, and {@code z}, one could write:
 130     *
 131     * <blockquote><pre>
 132     * @Override public int hashCode() {
 133     *     return Objects.hash(x, y, z);
 134     * }
 135     * </pre></blockquote>
 136     *
 137     * <b>Warning: When a single object reference is supplied, the returned
 138     * value does not equal the hash code of that object reference.</b> This
 139     * value can be computed by calling {@link #hashCode(Object)}.
 140     *
 141     * @param values the values to be hashed
 142     * @return a hash value of the sequence of input values
 143     * @see Arrays#hashCode(Object[])
 144     * @see List#hashCode
 145     */
 146     public static int hash(Object... values) {
 147         return Arrays.hashCode(values);
 148     }
 149 
 150     /**
 151      * Returns the result of calling {@code toString} for a non-{@code
 152      * null} argument and {@code "null"} for a {@code null} argument.
 153      *
 154      * @param o an object
 155      * @return the result of calling {@code toString} for a non-{@code
 156      * null} argument and {@code "null"} for a {@code null} argument
 157      * @see Object#toString
 158      * @see String#valueOf(Object)
 159      */
 160     public static String toString(Object o) {
 161         return String.valueOf(o);
 162     }
 163 
 164     /**
 165      * Returns the result of calling {@code toString} on the first
 166      * argument if the first argument is not {@code null} and returns
 167      * the second argument otherwise.
 168      *
 169      * @param o an object
 170      * @param nullDefault string to return if the first argument is
 171      *        {@code null}
 172      * @return the result of calling {@code toString} on the first
 173      * argument if it is not {@code null} and the second argument
 174      * otherwise.
 175      * @see Objects#toString(Object)
 176      */
 177     public static String toString(Object o, String nullDefault) {
 178         return (o != null) ? o.toString() : nullDefault;
 179     }
 180 
 181     /**
 182      * Returns 0 if the arguments are identical and {@code
 183      * c.compare(a, b)} otherwise.
 184      * Consequently, if both arguments are {@code null} 0
 185      * is returned.
 186      *
 187      * <p>Note that if one of the arguments is {@code null}, a {@code
 188      * NullPointerException} may or may not be thrown depending on
 189      * what ordering policy, if any, the {@link Comparator Comparator}
 190      * chooses to have for {@code null} values.
 191      *
 192      * @param <T> the type of the objects being compared
 193      * @param a an object
 194      * @param b an object to be compared with {@code a}
 195      * @param c the {@code Comparator} to compare the first two arguments
 196      * @return 0 if the arguments are identical and {@code
 197      * c.compare(a, b)} otherwise.
 198      * @see Comparable
 199      * @see Comparator
 200      */
 201     public static <T> int compare(T a, T b, Comparator<? super T> c) {
 202         return (a == b) ? 0 :  c.compare(a, b);
 203     }
 204 
 205     /**
 206      * Checks that the specified object reference is not {@code null}. This
 207      * method is designed primarily for doing parameter validation in methods
 208      * and constructors, as demonstrated below:
 209      * <blockquote><pre>
 210      * public Foo(Bar bar) {
 211      *     this.bar = Objects.requireNonNull(bar);
 212      * }
 213      * </pre></blockquote>
 214      *
 215      * @param obj the object reference to check for nullity
 216      * @param <T> the type of the reference
 217      * @return {@code obj} if not {@code null}
 218      * @throws NullPointerException if {@code obj} is {@code null}
 219      */
 220     public static <T> T requireNonNull(T obj) {
 221         if (obj == null)
 222             throw new NullPointerException();
 223         return obj;
 224     }
 225 
 226     /**
 227      * Checks that the specified object reference is not {@code null} and
 228      * throws a customized {@link NullPointerException} if it is. This method
 229      * is designed primarily for doing parameter validation in methods and
 230      * constructors with multiple parameters, as demonstrated below:
 231      * <blockquote><pre>
 232      * public Foo(Bar bar, Baz baz) {
 233      *     this.bar = Objects.requireNonNull(bar, "bar must not be null");
 234      *     this.baz = Objects.requireNonNull(baz, "baz must not be null");
 235      * }
 236      * </pre></blockquote>
 237      *
 238      * @param obj     the object reference to check for nullity
 239      * @param message detail message to be used in the event that a {@code
 240      *                NullPointerException} is thrown
 241      * @param <T> the type of the reference
 242      * @return {@code obj} if not {@code null}
 243      * @throws NullPointerException if {@code obj} is {@code null}
 244      */
 245     public static <T> T requireNonNull(T obj, String message) {
 246         if (obj == null)
 247             throw new NullPointerException(message);
 248         return obj;
 249     }
 250 
 251     /**
 252      * Returns {@code true} if the provided reference is {@code null} otherwise
 253      * returns {@code false}.
 254      *
 255      * @apiNote This method exists to be used as a
 256      * {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
 257      *
 258      * @param obj a reference to be checked against {@code null}
 259      * @return {@code true} if the provided reference is {@code null} otherwise
 260      * {@code false}
 261      *
 262      * @see java.util.function.Predicate
 263      * @since 1.8
 264      */
 265     public static boolean isNull(Object obj) {
 266         return obj == null;
 267     }
 268 
 269     /**
 270      * Returns {@code true} if the provided reference is non-{@code null}
 271      * otherwise returns {@code false}.
 272      *
 273      * @apiNote This method exists to be used as a
 274      * {@link java.util.function.Predicate}, {@code filter(Objects::nonNull)}
 275      *
 276      * @param obj a reference to be checked against {@code null}
 277      * @return {@code true} if the provided reference is non-{@code null}
 278      * otherwise {@code false}
 279      *
 280      * @see java.util.function.Predicate
 281      * @since 1.8
 282      */
 283     public static boolean nonNull(Object obj) {
 284         return obj != null;
 285     }
 286 
 287     /**
 288      * Returns the first argument if it is non-{@code null} and
 289      * otherwise returns the non-{@code null} second argument.
 290      *
 291      * @param obj an object
 292      * @param defaultObj a non-{@code null} object to return if the first argument
 293      *                   is {@code null}
 294      * @param <T> the type of the reference
 295      * @return the first argument if it is non-{@code null} and
 296      *        otherwise the second argument if it is non-{@code null}
 297      * @throws NullPointerException if both {@code obj} is null and
 298      *        {@code defaultObj} is {@code null}
 299      * @since 9
 300      */
 301     public static <T> T requireNonNullElse(T obj, T defaultObj) {
 302         return (obj != null) ? obj : requireNonNull(defaultObj, "defaultObj");
 303     }
 304 
 305     /**
 306      * Returns the first argument if it is non-{@code null} and otherwise
 307      * returns the non-{@code null} value of {@code supplier.get()}.
 308      *
 309      * @param obj an object
 310      * @param supplier of a non-{@code null} object to return if the first argument
 311      *                 is {@code null}
 312      * @param <T> the type of the first argument and return type
 313      * @return the first argument if it is non-{@code null} and otherwise
 314      *         the value from {@code supplier.get()} if it is non-{@code null}
 315      * @throws NullPointerException if both {@code obj} is null and
 316      *        either the {@code supplier} is {@code null} or
 317      *        the {@code supplier.get()} value is {@code null}
 318      * @since 9
 319      */
 320     public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) {
 321         return (obj != null) ? obj
 322                 : requireNonNull(requireNonNull(supplier, "supplier").get(), "supplier.get()");
 323     }
 324 
 325     /**
 326      * Checks that the specified object reference is not {@code null} and
 327      * throws a customized {@link NullPointerException} if it is.
 328      *
 329      * <p>Unlike the method {@link #requireNonNull(Object, String)},
 330      * this method allows creation of the message to be deferred until
 331      * after the null check is made. While this may confer a
 332      * performance advantage in the non-null case, when deciding to
 333      * call this method care should be taken that the costs of
 334      * creating the message supplier are less than the cost of just
 335      * creating the string message directly.
 336      *
 337      * @param obj     the object reference to check for nullity
 338      * @param messageSupplier supplier of the detail message to be
 339      * used in the event that a {@code NullPointerException} is thrown
 340      * @param <T> the type of the reference
 341      * @return {@code obj} if not {@code null}
 342      * @throws NullPointerException if {@code obj} is {@code null}
 343      * @since 1.8
 344      */
 345     public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
 346         if (obj == null)
 347             throw new NullPointerException(messageSupplier.get());
 348         return obj;
 349     }
 350 
 351     /**
 352      * Maps out-of-bounds values to a runtime exception.
 353      *
 354      * @param checkKind the kind of bounds check, whose name may correspond
 355      *        to the name of one of the range check methods, checkIndex,
 356      *        checkFromToIndex, checkFromIndexSize
 357      * @param args the out-of-bounds arguments that failed the range check.
 358      *        If the checkKind corresponds a the name of a range check method
 359      *        then the bounds arguments are those that can be passed in order
 360      *        to the method.
 361      * @param oobef the exception formatter that when applied with a checkKind
 362      *        and a list out-of-bounds arguments returns a runtime exception.
 363      *        If {@code null} then, it is as if an exception formatter was
 364      *        supplied that returns {@link IndexOutOfBoundsException} for any
 365      *        given arguments.
 366      * @return the runtime exception
 367      */
 368     private static RuntimeException outOfBounds(
 369             BiFunction<String, List<Integer>, ? extends RuntimeException> oobef,
 370             String checkKind,
 371             Integer... args) {
 372         List<Integer> largs = List.of(args);
 373         RuntimeException e = oobef == null
 374                              ? null : oobef.apply(checkKind, largs);
 375         return e == null
 376                ? new IndexOutOfBoundsException(outOfBoundsMessage(checkKind, largs)) : e;
 377     }
 378 
 379     // Specific out-of-bounds exception producing methods that avoid
 380     // the varargs-based code in the critical methods there by reducing their
 381     // the byte code size, and therefore less likely to peturb inlining
 382 
 383     private static RuntimeException outOfBoundsCheckIndex(
 384             BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
 385             int index, int length) {
 386         return outOfBounds(oobe, "checkIndex", index, length);
 387     }
 388 
 389     private static RuntimeException outOfBoundsCheckFromToIndex(
 390             BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
 391             int fromIndex, int toIndex, int length) {
 392         return outOfBounds(oobe, "checkFromToIndex", fromIndex, toIndex, length);
 393     }
 394 
 395     private static RuntimeException outOfBoundsCheckFromIndexSize(
 396             BiFunction<String, List<Integer>, ? extends RuntimeException> oobe,
 397             int fromIndex, int size, int length) {
 398         return outOfBounds(oobe, "checkFromIndexSize", fromIndex, size, length);
 399     }
 400 
 401     /**
 402      * Returns an out-of-bounds exception formatter from an given exception
 403      * factory.  The exception formatter is a function that formats an
 404      * out-of-bounds message from its arguments and applies that message to the
 405      * given exception factory to produce and relay an exception.
 406      *
 407      * <p>The exception formatter accepts two arguments: a {@code String}
 408      * describing the out-of-bounds range check that failed, referred to as the
 409      * <em>check kind</em>; and a {@code List<Integer>} containing the
 410      * out-of-bound integer values that failed the check.  The list of
 411      * out-of-bound values is not modified.
 412      *
 413      * <p>Three check kinds are supported {@code checkIndex},
 414      * {@code checkFromToIndex} and {@code checkFromIndexSize} corresponding
 415      * respectively to the specified application of an exception formatter as an
 416      * argument to the out-of-bounds range check methods
 417      * {@link #checkIndex(int, int, BiFunction) checkIndex},
 418      * {@link #checkFromToIndex(int, int, int, BiFunction) checkFromToIndex}, and
 419      * {@link #checkFromIndexSize(int, int, int, BiFunction) checkFromIndexSize}.
 420      * Thus a supported check kind corresponds to a method name and the
 421      * out-of-bound integer values correspond to method argument values, in
 422      * order, preceding the exception formatter argument (similar in many
 423      * respects to the form of arguments required for a reflective invocation of
 424      * such a range check method).
 425      *
 426      * <p>Formatter arguments conforming to such supported check kinds will
 427      * produce specific exception messages describing failed out-of-bounds
 428      * checks.  Otherwise, more generic exception messages will be produced in
 429      * any of the following cases: the check kind is supported but fewer
 430      * or more out-of-bounds values are supplied, the check kind is not
 431      * supported, the check kind is {@code null}, or the list of out-of-bound
 432      * values is {@code null}.
 433      *
 434      * @apiNote
 435      * This method produces an out-of-bounds exception formatter that can be
 436      * passed as an argument to any of the supported out-of-bounds range check
 437      * methods declared by {@code Objects}.  For example, a formatter producing
 438      * an {@code ArrayIndexOutOfBoundsException} may be produced and stored on a
 439      * {@code static final} field as follows:
 440      * <pre>{@code
 441      * static final
 442      * BiFunction<String, List<Integer>, ArrayIndexOutOfBoundsException> AIOOBEF =
 443      *     outOfBoundsExceptionFormatter(ArrayIndexOutOfBoundsException::new);
 444      * }</pre>
 445      * The formatter instance {@code AIOOBEF} may be passed as an argument to an
 446      * out-of-bounds range check method, such as checking if an {@code index}
 447      * is within the bounds of a {@code limit}:
 448      * <pre>{@code
 449      * checkIndex(index, limit, AIOOBEF);
 450      * }</pre>
 451      * If the bounds check fails then the range check method will throw an
 452      * {@code ArrayIndexOutOfBoundsException} with an appropriate exception
 453      * message that is a produced from {@code AIOOBEF} as follows:
 454      * <pre>{@code
 455      * AIOOBEF.apply("checkIndex", List.of(index, limit));
 456      * }</pre>
 457      *
 458      * @param f the exception factory, that produces an exception from a message
 459      *        where the message is produced and formatted by the returned
 460      *        exception formatter.  If this factory is stateless and side-effect
 461      *        free then so is the returned formatter.
 462      *        Exceptions thrown by the factory are relayed to the caller
 463      *        of the returned formatter.
 464      * @param <X> the type of runtime exception to be returned by the given
 465      *        exception factory and relayed by the exception formatter
 466      * @return the out-of-bounds exception formatter
 467      */
 468     public static <X extends RuntimeException>
 469     BiFunction<String, List<Integer>, X> outOfBoundsExceptionFormatter(Function<String, X> f) {
 470         // Use anonymous class to avoid bootstrap issues if this method is
 471         // used early in startup
 472         return new BiFunction<String, List<Integer>, X>() {
 473             @Override
 474             public X apply(String checkKind, List<Integer> args) {
 475                 return f.apply(outOfBoundsMessage(checkKind, args));
 476             }
 477         };
 478     }
 479 
 480     private static String outOfBoundsMessage(String checkKind, List<Integer> args) {
 481         if (checkKind == null && args == null) {
 482             return String.format("Range check failed");
 483         } else if (checkKind == null) {
 484             return String.format("Range check failed: %s", args);
 485         } else if (args == null) {
 486             return String.format("Range check failed: %s", checkKind);
 487         }
 488 
 489         int argSize = 0;
 490         switch (checkKind) {
 491             case "checkIndex":
 492                 argSize = 2;
 493                 break;
 494             case "checkFromToIndex":
 495             case "checkFromIndexSize":
 496                 argSize = 3;
 497                 break;
 498             default:
 499         }
 500 
 501         // Switch to default if fewer or more arguments than required are supplied
 502         switch ((args.size() != argSize) ? "" : checkKind) {
 503             case "checkIndex":
 504                 return String.format("Index %d out-of-bounds for length %d",
 505                                      args.get(0), args.get(1));
 506             case "checkFromToIndex":
 507                 return String.format("Range [%d, %d) out-of-bounds for length %d",
 508                                      args.get(0), args.get(1), args.get(2));
 509             case "checkFromIndexSize":
 510                 return String.format("Range [%d, %<d + %d) out-of-bounds for length %d",
 511                                      args.get(0), args.get(1), args.get(2));
 512             default:
 513                 return String.format("Range check failed: %s %s", checkKind, args);
 514         }
 515     }
 516 
 517     /**
 518      * Checks if the {@code index} is within the bounds of the range from
 519      * {@code 0} (inclusive) to {@code length} (exclusive).
 520      *
 521      * <p>The {@code index} is defined to be out-of-bounds if any of the
 522      * following inequalities is true:
 523      * <ul>
 524      *  <li>{@code index < 0}</li>
 525      *  <li>{@code index >= length}</li>
 526      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
 527      * </ul>
 528      *
 529      * <p>This method behaves as if {@link #checkIndex(int, int, BiFunction)}
 530      * was called with same out-of-bounds arguments and an exception formatter
 531      * argument produced from an invocation of
 532      * {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} (though it may
 533      * be more efficient).
 534      *
 535      * @param index the index
 536      * @param length the upper-bound (exclusive) of the range
 537      * @return {@code index} if it is within bounds of the range
 538      * @throws IndexOutOfBoundsException if the {@code index} is out-of-bounds
 539      * @since 9
 540      */
 541     public static
 542     int checkIndex(int index, int length) {
 543         return checkIndex(index, length, null);
 544     }
 545 
 546     /**
 547      * Checks if the {@code index} is within the bounds of the range from
 548      * {@code 0} (inclusive) to {@code length} (exclusive).
 549      *
 550      * <p>The {@code index} is defined to be out-of-bounds if any of the
 551      * following inequalities is true:
 552      * <ul>
 553      *  <li>{@code index < 0}</li>
 554      *  <li>{@code index >= length}</li>
 555      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
 556      * </ul>
 557      *
 558      * <p>If the {@code index} is out-of-bounds, then a runtime exception is
 559      * thrown that is the result of applying the following arguments to the
 560      * exception formatter: the name of this method, {@code checkIndex};
 561      * and an unmodifiable list integers whose values are, in order, the
 562      * out-of-bounds arguments {@code index} and {@code length}.
 563      *
 564      * @param <X> the type of runtime exception to throw if the arguments are
 565      *        out-of-bounds
 566      * @param index the index
 567      * @param length the upper-bound (exclusive) of the range
 568      * @param oobef the exception formatter that when applied with this
 569      *        method name and out-of-bounds arguments returns a runtime
 570      *        exception.  If {@code null} or returns {@code null} then, it is as
 571      *        if an exception formatter produced from an invocation of
 572      *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
 573      *        instead (though it may be more efficient).
 574      *        Exceptions thrown by the formatter are relayed to the caller.
 575      * @return {@code index} if it is within bounds of the range
 576      * @throws X if the {@code index} is out-of-bounds and the exception
 577      *         formatter is non-{@code null}
 578      * @throws IndexOutOfBoundsException if the {@code index} is out-of-bounds
 579      *         and the exception formatter is {@code null}
 580      * @since 9
 581      *
 582      * @implNote
 583      * This method is made intrinsic in optimizing compilers to guide them to
 584      * perform unsigned comparisons of the index and length when it is known the
 585      * length is a non-negative value (such as that of an array length or from
 586      * the upper bound of a loop)
 587     */
 588     @HotSpotIntrinsicCandidate
 589     public static <X extends RuntimeException>
 590     int checkIndex(int index, int length,
 591                    BiFunction<String, List<Integer>, X> oobef) {
 592         if (index < 0 || index >= length)
 593             throw outOfBoundsCheckIndex(oobef, index, length);
 594         return index;
 595     }
 596 
 597     /**
 598      * Checks if the sub-range from {@code fromIndex} (inclusive) to
 599      * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
 600      * (inclusive) to {@code length} (exclusive).
 601      *
 602      * <p>The sub-range is defined to be out-of-bounds if any of the following
 603      * inequalities is true:
 604      * <ul>
 605      *  <li>{@code fromIndex < 0}</li>
 606      *  <li>{@code fromIndex > toIndex}</li>
 607      *  <li>{@code toIndex > length}</li>
 608      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
 609      * </ul>
 610      *
 611      * <p>This method behaves as if {@link #checkFromToIndex(int, int, int, BiFunction)}
 612      * was called with same out-of-bounds arguments and an exception formatter
 613      * argument produced from an invocation of
 614      * {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} (though it may
 615      * be more efficient).
 616      *
 617      * @param fromIndex the lower-bound (inclusive) of the sub-range
 618      * @param toIndex the upper-bound (exclusive) of the sub-range
 619      * @param length the upper-bound (exclusive) the range
 620      * @return {@code fromIndex} if the sub-range within bounds of the range
 621      * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds
 622      * @since 9
 623      */
 624     public static
 625     int checkFromToIndex(int fromIndex, int toIndex, int length) {
 626         return checkFromToIndex(fromIndex, toIndex, length, null);
 627     }
 628 
 629     /**
 630      * Checks if the sub-range from {@code fromIndex} (inclusive) to
 631      * {@code toIndex} (exclusive) is within the bounds of range from {@code 0}
 632      * (inclusive) to {@code length} (exclusive).
 633      *
 634      * <p>The sub-range is defined to be out-of-bounds if any of the following
 635      * inequalities is true:
 636      * <ul>
 637      *  <li>{@code fromIndex < 0}</li>
 638      *  <li>{@code fromIndex > toIndex}</li>
 639      *  <li>{@code toIndex > length}</li>
 640      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
 641      * </ul>
 642      *
 643      * <p>If the sub-range  is out-of-bounds, then a runtime exception is
 644      * thrown that is the result of applying the following arguments to the
 645      * exception formatter: the name of this method, {@code checkFromToIndex};
 646      * and an unmodifiable list integers whose values are, in order, the
 647      * out-of-bounds arguments {@code fromIndex}, {@code toIndex}, and {@code length}.
 648      *
 649      * @param <X> the type of runtime exception to throw if the arguments are
 650      *        out-of-bounds
 651      * @param fromIndex the lower-bound (inclusive) of the sub-range
 652      * @param toIndex the upper-bound (exclusive) of the sub-range
 653      * @param length the upper-bound (exclusive) the range
 654      * @param oobef the exception formatter that when applied with this
 655      *        method name and out-of-bounds arguments returns a runtime
 656      *        exception.  If {@code null} or returns {@code null} then, it is as
 657      *        if an exception formatter produced from an invocation of
 658      *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
 659      *        instead (though it may be more efficient).
 660      *        Exceptions thrown by the formatter are relayed to the caller.
 661      * @return {@code fromIndex} if the sub-range within bounds of the range
 662      * @throws X if the sub-range is out-of-bounds and the exception factory
 663      *         function is non-{@code null}
 664      * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds and
 665      *         the exception factory function is {@code null}
 666      * @since 9
 667      */
 668     public static <X extends RuntimeException>
 669     int checkFromToIndex(int fromIndex, int toIndex, int length,
 670                          BiFunction<String, List<Integer>, X> oobef) {
 671         if (fromIndex < 0 || fromIndex > toIndex || toIndex > length)
 672             throw outOfBoundsCheckFromToIndex(oobef, fromIndex, toIndex, length);
 673         return fromIndex;
 674     }
 675 
 676     /**
 677      * Checks if the sub-range from {@code fromIndex} (inclusive) to
 678      * {@code fromIndex + size} (exclusive) is within the bounds of range from
 679      * {@code 0} (inclusive) to {@code length} (exclusive).
 680      *
 681      * <p>The sub-range is defined to be out-of-bounds if any of the following
 682      * inequalities is true:
 683      * <ul>
 684      *  <li>{@code fromIndex < 0}</li>
 685      *  <li>{@code size < 0}</li>
 686      *  <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
 687      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
 688      * </ul>
 689      *
 690      * <p>This method behaves as if {@link #checkFromIndexSize(int, int, int, BiFunction)}
 691      * was called with same out-of-bounds arguments and an exception formatter
 692      * argument produced from an invocation of
 693      * {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} (though it may
 694      * be more efficient).
 695      *
 696      * @param fromIndex the lower-bound (inclusive) of the sub-interval
 697      * @param size the size of the sub-range
 698      * @param length the upper-bound (exclusive) of the range
 699      * @return {@code fromIndex} if the sub-range within bounds of the range
 700      * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds
 701      * @since 9
 702      */
 703     public static
 704     int checkFromIndexSize(int fromIndex, int size, int length) {
 705         return checkFromIndexSize(fromIndex, size, length, null);
 706     }
 707 
 708     /**
 709      * Checks if the sub-range from {@code fromIndex} (inclusive) to
 710      * {@code fromIndex + size} (exclusive) is within the bounds of range from
 711      * {@code 0} (inclusive) to {@code length} (exclusive).
 712      *
 713      * <p>The sub-range is defined to be out-of-bounds if any of the following
 714      * inequalities is true:
 715      * <ul>
 716      *  <li>{@code fromIndex < 0}</li>
 717      *  <li>{@code size < 0}</li>
 718      *  <li>{@code fromIndex + size > length}, taking into account integer overflow</li>
 719      *  <li>{@code length < 0}, which is implied from the former inequalities</li>
 720      * </ul>
 721      *
 722      * <p>If the sub-range  is out-of-bounds, then a runtime exception is
 723      * thrown that is the result of applying the following arguments to the
 724      * exception formatter: the name of this method, {@code checkFromIndexSize};
 725      * and an unmodifiable list integers whose values are, in order, the
 726      * out-of-bounds arguments {@code fromIndex}, {@code size}, and
 727      * {@code length}.
 728      *
 729      * @param <X> the type of runtime exception to throw if the arguments are
 730      *        out-of-bounds
 731      * @param fromIndex the lower-bound (inclusive) of the sub-interval
 732      * @param size the size of the sub-range
 733      * @param length the upper-bound (exclusive) of the range
 734      * @param oobef the exception formatter that when applied with this
 735      *        method name and out-of-bounds arguments returns a runtime
 736      *        exception.  If {@code null} or returns {@code null} then, it is as
 737      *        if an exception formatter produced from an invocation of
 738      *        {@code outOfBoundsExceptionFormatter(IndexOutOfBounds::new)} is used
 739      *        instead (though it may be more efficient).
 740      *        Exceptions thrown by the formatter are relayed to the caller.
 741      * @return {@code fromIndex} if the sub-range within bounds of the range
 742      * @throws X if the sub-range is out-of-bounds and the exception factory
 743      *         function is non-{@code null}
 744      * @throws IndexOutOfBoundsException if the sub-range is out-of-bounds and
 745      *         the exception factory function is {@code null}
 746      * @since 9
 747      */
 748     public static <X extends RuntimeException>
 749     int checkFromIndexSize(int fromIndex, int size, int length,
 750                            BiFunction<String, List<Integer>, X> oobef) {
 751         if ((length | fromIndex | size) < 0 || size > length - fromIndex)
 752             throw outOfBoundsCheckFromIndexSize(oobef, fromIndex, size, length);
 753         return fromIndex;
 754     }
 755 }