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.

JavaData Integrity

Code

snippet
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

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:`.