krahets/hello-algo · error · IndexOutOfBoundsException

индекс выходит за границы

Error message

индекс выходит за границы

What it means

Russian-translation twin of error 200: thrown by get() in MyList (ru/codes/java). Same guard — index must be 0 <= index < size. The message 'индекс выходит за границы' means 'index goes out of bounds'. The class is the same pedagogical dynamic-array reimplementation; only the localized string differs from the ja build.

Source

Thrown at ru/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. Bounds-check before access: `if (index >= 0 && index < list.size()) list.get(index);`
  2. Use `< list.size()` as the loop bound, reading size() live each iteration.
  3. Distinguish size() (live count) from capacity() (backing length).
  4. Switch to java.util.ArrayList for non-pedagogical use.

Example fix

// before
for (int i = 0; i <= list.capacity(); i++) list.get(i); // IndexOutOfBoundsException
// after
for (int i = 0; i < list.size(); i++) list.get(i);
Defensive patterns

Strategy: validation

Validate before calling

if (index < 0 || index >= list.size()) {
    throw new IllegalArgumentException("bad index: " + index);
}
int v = list.get(index);

Try / catch

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

Prevention

When it happens

Trigger: myList.get(-1); myList.get(size); myList.get(0) on an empty list; using capacity() instead of size() as a loop ceiling; index sourced from a collection of different length.

Common situations: Off-by-one read loop (`<=` instead of `<`); capacity/size confusion; stale index after concurrent remove; 1-based indexing assumptions.

Related errors


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