krahets/hello-algo · error · IndexOutOfBoundsException

索引越界

Error message

索引越界

What it means

A Java IndexOutOfBoundsException with message '索引越界' thrown by get() in MyList (my_list.java:37). MyList is a hand-rolled dynamic array; get(index) returns arr[index] after checking 0 <= index < size. The guard prevents reading uninitialized/garbage slots beyond the logical element count (size) even though the backing array may be larger (capacity).

Source

Thrown at codes/java/chapter_array_and_linkedlist/my_list.java:37

    public MyList() {
        arr = new int[capacity];
    }

    /* 获取列表长度(当前元素数量) */
    public int size() {
        return size;
    }

    /* 获取列表容量 */
    public int capacity() {
        return capacity;
    }

    /* 访问元素 */
    public int get(int index) {
        // 索引如果越界,则抛出异常,下同
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("索引越界");
        return arr[index];
    }

    /* 更新元素 */
    public void set(int index, int num) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("索引越界");
        arr[index] = num;
    }

    /* 在尾部添加元素 */
    public void add(int num) {
        // 元素数量超出容量时,触发扩容机制
        if (size == capacity())
            extendCapacity();
        arr[size] = num;
        // 更新元素数量
        size++;

View on GitHub (pinned to 69932aed18)

Solutions

  1. Ensure 0 <= index < list.size() before get.
  2. Always bound loops with `< list.size()`, never `<= size` or `< list.capacity()`.
  3. Recompute indices after any insert/remove since they shift elements.
  4. Use size(), not capacity(), as the valid range upper bound.

Example fix

// before: off-by-one reads one past the last element
for (int i = 0; i <= list.size(); i++) {
    int v = list.get(i);
}

// after: correct bound
for (int i = 0; i < list.size(); i++) {
    int v = list.get(i);
}
Defensive patterns

Strategy: validation

Validate before calling

// Validate index before MyList.get
public static int safeGet(MyList list, int index) {
    if (index < 0 || index >= list.size()) {
        throw new IllegalArgumentException("index " + index + " out of [0," + list.size() + ")");
    }
    return list.get(index);
}

Type guard

// Java has no structural type guards; use an explicit bounds predicate
static boolean inBounds(MyList list, int index) {
    return index >= 0 && index < list.size();
}

Try / catch

try {
    int v = list.get(index);
} catch (IndexOutOfBoundsException e) {
    // index outside [0, size); log and recover
}

Prevention

When it happens

Trigger: Calling list.get(index) where index < 0 or index >= list.size(). Reading past the last logical element, or reading before the first; using list.capacity() (the backing array length) as the upper bound instead of list.size().

Common situations: Off-by-one loops (`<= size` instead of `< size`); confusing size() (element count) with capacity() (array length); using an index captured before remove() shifted elements left; stale indices after insert() shifted elements right.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/9993373f593b44a0. Report an issue: GitHub.