Objects checkIndex Bounds Checking
Objects.checkIndex and checkFromToIndex return their argument when bounds hold and throw IndexOutOfBoundsException with a precise message when they do not.
Code
import java.util.List;
import java.util.Objects;
public class BoundsChecking {
public static void main(String[] args) {
List<String> stages = List.of("ingest", "decode", "render");
// 合法时原样返回索引,越界时抛 IndexOutOfBoundsException
int middle = Objects.checkIndex(1, stages.size());
System.out.println(stages.get(middle));
try {
Objects.checkIndex(3, stages.size());
} catch (IndexOutOfBoundsException bad) {
System.out.println("blocked: " + bad.getMessage());
}
// 范围版本:一次校验 [from, to) 整段都落在 0..length 内,合法时返回 from
int start = Objects.checkFromToIndex(1, 3, stages.size());
System.out.println("range ok from: " + start);
try {
Objects.checkFromToIndex(2, 5, stages.size());
} catch (IndexOutOfBoundsException bad) {
System.out.println("range blocked: " + bad.getMessage());
}
}
}How the snippet works
The moving parts are the class BoundsChecking and the function main.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
Signature: public static void main(String[] args)
Each step stamps its own output — blocked:, range ok from:, range blocked: — when the file runs.
Key statements
List<String> stages = List.of("ingest", "decode", "render");
int start = Objects.checkFromToIndex(1, 3, stages.size());
int middle = Objects.checkIndex(1, stages.size());
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What does Objects checkIndex Bounds Checking print when run?
- Execute the whole file; each printed line is prefixed with a label like `blocked:`, `range ok from:`, `range blocked:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.