TheAlgorithms/Java · error · IndexOutOfBoundsException
Position out of bounds
Error message
Position out of bounds
What it means
Thrown by CircleLinkedList.remove(int pos) when pos >= size or pos < 0. The list uses 0-based logical positions and the guard validates the index before walking the node chain. An invalid pos would dereference a null node pointer.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java:109
sb.append(", ");
}
current = current.next;
}
sb.append(" ]");
return sb.toString();
}
/**
* Removes and returns the element at the specified position in the list.
* Throws an IndexOutOfBoundsException if the position is invalid.
*
* @param pos the position of the element to remove
* @return the value of the removed element
* @throws IndexOutOfBoundsException if the position is out of range
*/
public E remove(int pos) {
if (pos >= size || pos < 0) {
throw new IndexOutOfBoundsException("Position out of bounds");
}
Node<E> before = head;
for (int i = 1; i <= pos; i++) {
before = before.next;
}
Node<E> destroy = before.next;
E saved = destroy.value;
before.next = destroy.next;
if (destroy == tail) {
tail = before;
}
destroy = null;
size--;
return saved;
}
}View on GitHub (pinned to fdfb9a395b)
Solutions
- Validate `pos >= 0 && pos < list.size()` before remove.
- Guard for empty list separately.
- Use `i < list.size()` (strict) in removal loops, and recompute size each iteration since remove shrinks it.
- When removing multiple elements, decrement indices or iterate in reverse.
Example fix
// before
for (int i = 0; i <= list.size(); i++) list.remove(i);
// after
while (!list.isEmpty()) {
list.remove(0);
} Defensive patterns
Strategy: validation
Validate before calling
if (pos >= 0 && pos < list.size()) {
return list.remove(pos);
} Try / catch
try {
return list.remove(pos);
} catch (IndexOutOfBoundsException e) {
// invalid pos — skip
} Prevention
- Use strict `<` against size in loops, never `<=`.
- Recompute size each iteration when removing in a loop.
- Iterate in reverse when removing multiple indexed elements.
When it happens
Trigger: Calling remove(size) (off-by-one treating size as a valid index). Calling remove on an empty list (size=0, any non-negative pos fails). Passing a negative index.
Common situations: Loop `for (int i = 0; i <= list.size(); i++) remove(i)` including the size boundary. Removing by an index from a parallel array sized differently. Negative index from an arithmetic underflow.
Related errors
- Position out of bounds
- Index: ${index}, Size: ${size}
- ${position}
- Cannot add null element to the list
- Cannot add null element to the list
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/479ae4f4fda4d61f.
Report an issue: GitHub.