TheAlgorithms/Java · error · IndexOutOfBoundsException
Index cannot be negative.
Error message
Index cannot be negative.
What it means
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[].
Source
Thrown at src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java:71
* @param element the element to be added to the array
*/
public void add(final E element) {
ensureCapacity(size + 1);
elements[size++] = element;
modCount++; // Increment modification count
}
/**
* Places an element at the specified index, expanding capacity if necessary.
*
* @param index the index at which the element is to be placed
* @param element the element to be inserted at the specified index
* @throws IndexOutOfBoundsException if index is less than 0 or greater than or
* equal to the number of elements
*/
public void put(final int index, E element) {
if (index < 0) {
throw new IndexOutOfBoundsException("Index cannot be negative.");
}
ensureCapacity(index + 1);
elements[index] = element;
if (index >= size) {
size = index + 1;
}
modCount++; // Increment modification count
}
/**
* Retrieves the element at the specified index.
*
* @param index the index of the element to retrieve
* @return the element at the specified index
* @throws IndexOutOfBoundsException if index is less than 0 or greater than or
* equal to the current size
*/
@SuppressWarnings("unchecked")View on GitHub (pinned to fdfb9a395b)
Solutions
- Validate that index >= 0 before calling put()
- Use add(element) instead when you simply want to append
- Review index arithmetic for underflow conditions
Example fix
// before
array.put(currentPos - offset, value); // throws if offset > currentPos
// after
int idx = currentPos - offset;
if (idx < 0) throw new IllegalArgumentException("position underflow");
array.put(idx, value); Defensive patterns
Strategy: validation
Validate before calling
if (index < 0) {
throw new IllegalArgumentException("put index must be >= 0: " + index);
}
array.put(index, element); Try / catch
try {
array.put(index, element);
} catch (IndexOutOfBoundsException e) {
if (index < 0) {
array.put(0, element); // or handle error
} else throw e;
} Prevention
- 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)
When it happens
Trigger: Calling array.put(-1, element), or passing a computed index that evaluates to a negative number.
Common situations: 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.
Related errors
- Capacity cannot be negative.
- Index: {index}, Size: {size}
- Input cannot be negative
- The exponent must be positive
- Input must be a non-empty binary string.
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/6089da2a132e5942.
Report an issue: GitHub.