TheAlgorithms/Java · error · IndexOutOfBoundsException

${position}

Error message

${position}

What it means

Thrown by SinglyLinkedList.checkBounds(position, low, high) when position is outside [low, high]. The helper is called by indexed access methods (get, insertAt, etc.) to validate the position; it throws IndexOutOfBoundsException with just the offending position as its message.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java:395

    public int getNth(int index) {
        checkBounds(index, 0, size - 1);
        SinglyLinkedListNode cur = head;
        for (int i = 0; i < index; ++i) {
            cur = cur.next;
        }
        return cur.value;
    }

    /**
     * @param position to check position
     * @param low low index
     * @param high high index
     * @throws IndexOutOfBoundsException if {@code position} not in range
     * {@code low} to {@code high}
     */
    public void checkBounds(int position, int low, int high) {
        if (position > high || position < low) {
            throw new IndexOutOfBoundsException(position + "");
        }
    }

    /**
     * Driver Code
     */
    public static void main(String[] arg) {
        SinglyLinkedList list = new SinglyLinkedList();
        assert list.isEmpty();
        assert list.size() == 0 && list.count() == 0;
        assert list.toString().isEmpty();

        /* Test insert function */
        list.insertHead(5);
        list.insertHead(7);
        list.insertHead(10);
        list.insert(3);
        list.insertNth(1, 4);

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Validate `position >= low && position <= high` before the indexed call.
  2. Use strict `< list.size()` in iteration bounds.
  3. Recompute the list size before computing positions.
  4. For 0-based indexed access, ensure position is in [0, size-1].

Example fix

// before
int v = list.get(i); // i may equal size

// after
if (i < 0 || i >= list.size()) {
    throw new IndexOutOfBoundsException(i);
}
int v = list.get(i);
Defensive patterns

Strategy: validation

Validate before calling

if (position >= low && position <= high) {
    // safe to proceed with indexed access
}

Try / catch

try {
    return list.get(position);
} catch (IndexOutOfBoundsException e) {
    // position out of range
}

Prevention

When it happens

Trigger: Calling get(size) or any indexed method with position == size. Passing a negative position. Position computed from an external size that disagrees with the list's size.

Common situations: Off-by-one loop using `<=` against size. Stale position after concurrent modification. Index derived from a parallel array of different length.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/d52fb69b502a7331. Report an issue: GitHub.