ArrayList<E> · Java
add(E)
Appends an element at the end.
public boolean add(E e)
Complexity
| Best case | O(1) |
|---|---|
| Amortized | O(1) ("amortized constant time" is the documented guarantee) |
| Worst case | O(n) when the array grows |
| Extra space | O(1) amortized |
Store at index size. When full, Arrays.copyOf allocates a ~1.5× larger array and copies everything; geometric growth amortizes the copies.
Tested example
List<Integer> list = new ArrayList<>(2);
list.add(10);
list.add(20);
list.add(30); // full: grows the backing array (amortized constant time)
assert list.size() == 3;
Parameters
- e
- The element (null allowed).
Behaviour
- Returns
- Always true (the Collection contract).
- Errors and preconditions
- None in normal use (OutOfMemoryError at extreme sizes).
- Changes
- size increases by 1; may replace elementData.
- Memory and invalidation
- Growth allocates a new array. Fail-fast iterators throw afterwards.
See it step by step: the Dynamic arrays: capacity, resizing and amortized append lesson has an interactive 3D visualizer of the same mechanism.