ArrayList<E> · Java
add(int, E)
Inserts at a position and shifts later elements right.
public void add(int index, E element)
Complexity
| Best case | O(1) at the end |
|---|---|
| Worst case | O(n) at the front |
| Extra space | O(1) amortized |
System.arraycopy moves size − index references.
Tested example
List<String> list = new ArrayList<>(List.of("a", "c", "d"));
list.add(1, "b"); // shifts "c" and "d" right
assert list.equals(List.of("a", "b", "c", "d"));
try {
list.add(10, "x");
throw new AssertionError("expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
// index must be in 0..size()
}
Parameters
- index
- 0 ≤ index ≤ size().
- element
- The element.
Behaviour
- Returns
- Nothing.
- Errors and preconditions
- IndexOutOfBoundsException if index < 0 or index > size().
- Changes
- size increases by 1.
- Memory and invalidation
- May grow the array.
See it step by step: the Dynamic arrays: capacity, resizing and amortized append lesson has an interactive 3D visualizer of the same mechanism.