{"record":{"id":"6089da2a132e5942","repo":"TheAlgorithms/Java","slug":"index-cannot-be-negative","errorCode":null,"errorMessage":"Index cannot be negative.","messagePattern":"Index cannot be negative\\.","errorType":"exception","errorClass":"IndexOutOfBoundsException","httpStatus":null,"severity":"error","filePath":"src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java","lineNumber":71,"sourceCode":"     * @param element the element to be added to the array\n     */\n    public void add(final E element) {\n        ensureCapacity(size + 1);\n        elements[size++] = element;\n        modCount++; // Increment modification count\n    }\n\n    /**\n     * Places an element at the specified index, expanding capacity if necessary.\n     *\n     * @param index   the index at which the element is to be placed\n     * @param element the element to be inserted at the specified index\n     * @throws IndexOutOfBoundsException if index is less than 0 or greater than or\n     *                                   equal to the number of elements\n     */\n    public void put(final int index, E element) {\n        if (index < 0) {\n            throw new IndexOutOfBoundsException(\"Index cannot be negative.\");\n        }\n        ensureCapacity(index + 1);\n        elements[index] = element;\n        if (index >= size) {\n            size = index + 1;\n        }\n        modCount++; // Increment modification count\n    }\n\n    /**\n     * Retrieves the element at the specified index.\n     *\n     * @param index the index of the element to retrieve\n     * @return the element at the specified index\n     * @throws IndexOutOfBoundsException if index is less than 0 or greater than or\n     *                                   equal to the current size\n     */\n    @SuppressWarnings(\"unchecked\")","sourceCodeStart":53,"sourceCodeEnd":89,"githubUrl":"https://github.com/TheAlgorithms/Java/blob/fdfb9a395b310167a66bd29e311e36e0e3e9b964/src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java#L53-L89","documentation":"DynamicArray.put(index, element) rejects negative indices but allows any non-negative index — it expands capacity as needed via ensureCapacity. This differs from get() and remove() which also enforce an upper bound. The negative check prevents array-underflow issues in the backing Object[].","triggerScenarios":"Calling array.put(-1, element), or passing a computed index that evaluates to a negative number.","commonSituations":"Index derived from a subtraction that underflows (e.g., position - offset when offset > position). Circular-buffer or modular arithmetic logic producing negative values before the modulo is applied. Off-by-one in reverse iteration.","solutions":["Validate that index >= 0 before calling put()","Use add(element) instead when you simply want to append","Review index arithmetic for underflow conditions"],"exampleFix":"// before\narray.put(currentPos - offset, value); // throws if offset > currentPos\n\n// after\nint idx = currentPos - offset;\nif (idx < 0) throw new IllegalArgumentException(\"position underflow\");\narray.put(idx, value);","handlingStrategy":"validation","validationCode":"if (index < 0) {\n    throw new IllegalArgumentException(\"put index must be >= 0: \" + index);\n}\narray.put(index, element);","typeGuard":null,"tryCatchPattern":"try {\n    array.put(index, element);\n} catch (IndexOutOfBoundsException e) {\n    if (index < 0) {\n        array.put(0, element); // or handle error\n    } else throw e;\n}","preventionTips":["Check index >= 0 before put()","Use add() for appending when you do not need a specific position","Audit index arithmetic for underflow (subtraction producing negatives)"],"tags":["dynamic-array","index-bounds","validation"],"backgroundTag":null,"analyzedSha":"fdfb9a395b310167a66bd29e311e36e0e3e9b964","analyzedAt":"2026-08-13T23:36:13.315Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}