TheAlgorithms/Java · error · IndexOutOfBoundsException
Position out of bounds
Error message
Position out of bounds
What it means
Thrown by CircularDoublyLinkedList.remove(int pos) when pos >= size or pos < 0. The list uses 0-based positions and the guard prevents walking past the sentinel/head node. Removing an out-of-range index would corrupt the circular linkage.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedList.java:106
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 - pop operation
* @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> current = head.next;
for (int i = 0; i < pos; i++) {
current = current.next;
}
current.prev.next = current.next;
current.next.prev = current.prev;
E removedValue = current.value;
size--;
return removedValue;
}
}
View on GitHub (pinned to fdfb9a395b)
Solutions
- Check `pos >= 0 && pos < list.size()` before remove.
- Guard the empty-list case explicitly.
- Recompute the index or iterate in reverse when removing multiple elements.
- Use strict `<` in loop bounds, never `<=` against size.
Example fix
// before
list.remove(pos); // pos may be stale
// after
if (pos >= 0 && pos < list.size()) {
list.remove(pos);
} 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
} Prevention
- Validate position against [0, size-1] before remove.
- Recompute size during multi-remove loops.
- Avoid stale indices held across structural changes.
When it happens
Trigger: Calling remove on an empty list. Calling remove(size). Negative pos passed from an underflowed calculation.
Common situations: Index sourced from a different collection's size. Stale index held across prior removes. Off-by-one loop bound `i <= size`.
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/e9fd494f2fe2a27d.
Report an issue: GitHub.