krahets/hello-algo · error · IndexOutOfBoundsException

索引越界

Error message

索引越界

What it means

This is a hand-written dynamic-array list (my_list). The get(int index) accessor throws IndexOutOfBoundsException with the message "索引越界" ("index out of bounds") whenever the requested index falls outside the occupied element range [0, size-1]. Unlike java.util.ArrayList which tracks an internal capacity separately, this class uses a single `size` counter that records how many elements have actually been stored; the guard `index < 0 || index >= size` enforces that only occupied slots are readable.

Source

Thrown at zh-hant/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. Check the index against the list's current size before calling get(): if (index >= 0 && index < list.size()) { ... }
  2. Fix off-by-one loops: iterate i < list.size(), not i <= list.size().
  3. If you need a slot that may be empty, remember this list only exposes [0, size-1]; capacity() gives the backing array length, not valid element indices — never index by capacity().
  4. Wrap the call in try/catch(IndexOutOfBoundsException) only for genuinely unpredictable input; otherwise prefer pre-call validation.

Example fix

// before
int v = list.get(list.size());   // throws "索引越界"

// after
if (idx >= 0 && idx < list.size()) {
    int v = list.get(idx);
} else {
    // handle missing slot
}
Defensive patterns

Strategy: validation

Validate before calling

if (index < 0 || index >= list.size()) {
    // reject or clamp before calling get()
} else {
    int v = list.get(index);
}

Type guard

// index is an int; validate range against current size
boolean inRange = index >= 0 && index < list.size();

Try / catch

try {
    int v = list.get(index);
} catch (IndexOutOfBoundsException e) {
    // "索引越界": handle missing/out-of-range index
}

Prevention

When it happens

Trigger: Calling list.get(-1), list.get(list.size()), or list.get(anyIndex) after removing elements without the caller updating its cached size. Directly passing a loop counter that overshoots by one (e.g. `for (int i=0; i<=size; i++)`), or using an index that was valid before a remove()/insert() shift but stale afterwards.

Common situations: Off-by-one loop termination (`<=` instead of `<`); off-by-one after a bulk remove because `size()` changed mid-iteration; learning code where a student copies an ArrayList example but the custom list lacks ListIterator bounds; passing user/parsed input directly as an index without clamping.

Related errors


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