{"record":{"id":"fc68f8e05c3a3c8e","repo":"krahets/hello-algo","slug":"error-fc68f8","errorCode":null,"errorMessage":"索引越界","messagePattern":"索引越界","errorType":"exception","errorClass":"IndexOutOfBoundsException","httpStatus":null,"severity":"error","filePath":"zh-hant/codes/java/chapter_array_and_linkedlist/my_list.java","lineNumber":37,"sourceCode":"    public MyList() {\n        arr = new int[capacity];\n    }\n\n    /* 獲取串列長度（當前元素數量） */\n    public int size() {\n        return size;\n    }\n\n    /* 獲取串列容量 */\n    public int capacity() {\n        return capacity;\n    }\n\n    /* 訪問元素 */\n    public int get(int index) {\n        // 索引如果越界，則丟擲異常，下同\n        if (index < 0 || index >= size)\n            throw new IndexOutOfBoundsException(\"索引越界\");\n        return arr[index];\n    }\n\n    /* 更新元素 */\n    public void set(int index, int num) {\n        if (index < 0 || index >= size)\n            throw new IndexOutOfBoundsException(\"索引越界\");\n        arr[index] = num;\n    }\n\n    /* 在尾部新增元素 */\n    public void add(int num) {\n        // 元素數量超出容量時，觸發擴容機制\n        if (size == capacity())\n            extendCapacity();\n        arr[size] = num;\n        // 更新元素數量\n        size++;","sourceCodeStart":19,"sourceCodeEnd":55,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/zh-hant/codes/java/chapter_array_and_linkedlist/my_list.java#L19-L55","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Check the index against the list's current size before calling get(): if (index >= 0 && index < list.size()) { ... }","Fix off-by-one loops: iterate i < list.size(), not i <= list.size().","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().","Wrap the call in try/catch(IndexOutOfBoundsException) only for genuinely unpredictable input; otherwise prefer pre-call validation."],"exampleFix":"// before\nint v = list.get(list.size());   // throws \"索引越界\"\n\n// after\nif (idx >= 0 && idx < list.size()) {\n    int v = list.get(idx);\n} else {\n    // handle missing slot\n}","handlingStrategy":"validation","validationCode":"if (index < 0 || index >= list.size()) {\n    // reject or clamp before calling get()\n} else {\n    int v = list.get(index);\n}","typeGuard":"// index is an int; validate range against current size\nboolean inRange = index >= 0 && index < list.size();","tryCatchPattern":"try {\n    int v = list.get(index);\n} catch (IndexOutOfBoundsException e) {\n    // \"索引越界\": handle missing/out-of-range index\n}","preventionTips":["Always loop with i < list.size(), never i <= list.size().","Recompute size after any add/remove/insert before re-indexing.","Never index by capacity(); only [0, size-1] is valid.","Clamp external numeric input to [0, size-1] before use."],"tags":["java","data-structure","dynamic-array","index-bounds","off-by-one"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}