Objects.checkIndex
, introduced in Java 11, is a utility method for safely validating an index against a given range. It simplifies index validation by throwing well-defined exceptions with meaningful error messages if the index is out of bounds.
Syntax
public static int checkIndex(int index, int length)
- index: The index to check.
- length: The upper bound (exclusive) of the valid index range (0 to
length-1
).
If the index is within bounds (index >= 0
and index < length
), the method simply returns the index. Otherwise, it throws an IndexOutOfBoundsException
with a clear and informative message.
Example Usage
The method can be helpful when working with arrays, lists, or other collections where you need to validate that an index is within the permissible range.
Example: Validating Array Index
package org.kodejava.util;
import java.util.Objects;
public class Main {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int indexToAccess = 3; // Index we want to validate
try {
// Validate the index
Objects.checkIndex(indexToAccess, array.length);
// If valid, safely access the array element
System.out.println("Element at index " + indexToAccess + ": " + array[indexToAccess]);
} catch (IndexOutOfBoundsException e) {
System.err.println("Invalid index: " + e.getMessage());
}
}
}
Output (if indexToAccess = 3):
Element at index 3: 4
Output (if indexToAccess = 10, for example):
Invalid index: Index 10 out of bounds for length 5
When to Use
- Use
Objects.checkIndex
when you expect to handle invalid index scenarios explicitly via exceptions instead of relying on implicit array or list behavior. - It provides better readable error messages compared to manually performing index checks and throwing custom exceptions.
- It is typically used in contexts where throwing an
IndexOutOfBoundsException
is appropriate for invalid input.
Benefits
- Simpler and cleaner code for index validation.
- Automatically provides meaningful exception messages.
- Ensures a uniform approach to index validation in Java codebases.
Notes
- This method checks only one index at a time; use it in iterative or batch processing when validating multiple indices.
- It is part of the
java.util.Objects
utility class and requires Java 11 or later.