adam bien's blog

java.util.Objects: Useful Array Index Check Methods 📎

Objects ships with useful array index check methods:

checkIndex: Checks if the index is within the bounds of the range from 0 (inclusive) to length (exclusive).


@Test
public void checkIndex() {
    var index = 1;
    var length = 2;
    var actual = Objects.checkIndex(index, length);
    assertEquals(index, actual);

    assertThrows(IndexOutOfBoundsException.class, () -> {
        Objects.checkIndex(2,2);
    });
}

A violation (e.g. Objects.checkIndex(2, 2)) yields a throws an instance of IndexOutOfBoundsException with the following message: java.lang.IndexOutOfBoundsException: Index 2 out of bounds for length 2

checkFromToIndex: Checks if the sub-range from fromIndex (inclusive) to toIndex (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).


@Test
public void checkFromToIndex() {
    var fromIndex = 0;
    var toIndex = 0;
    var length = 4;
    var actual = Objects.checkFromToIndex(fromIndex, toIndex, length);
    assertEquals(fromIndex, actual);

    assertThrows(IndexOutOfBoundsException.class, () -> { 
        Objects.checkFromIndexSize(0, 5, 4);
    });
}    

checkFromIndexSize: Checks if the sub-range from fromIndex (inclusive) to fromIndex + size (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).


@Test
public void checkFromIndexSize() {
    var index = 0;
    var size = 3;
    var length = 4;
    var actual = Objects.checkFromIndexSize(index, size, length);
    assertEquals(index, actual);

    assertThrows(IndexOutOfBoundsException.class, () -> {
        //1 + 4 >= 4
        Objects.checkFromIndexSize(1, 4, 4);
    });
}