ArrayList<E> · Java
get / set
Reads or replaces the element at a position.
public E get(int index); public E set(int index, E element)
Complexity
| Best case | O(1) |
|---|---|
| Worst case | O(1) |
| Extra space | O(1) |
Direct array access; ArrayList implements the RandomAccess marker interface for exactly this reason.
Tested example
List<Integer> list = new ArrayList<>(List.of(1, 2, 3));
Integer previous = list.set(1, 20); // set returns the old element
assert previous == 2 && list.get(1) == 20;
try {
list.get(3);
throw new AssertionError("expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
// size(), not capacity, is the limit
}
Parameters
- index
- 0 ≤ index < size().
Behaviour
- Returns
- get: the element. set: the element previously at that position.
- Errors and preconditions
- IndexOutOfBoundsException if index < 0 or index ≥ size().
- Changes
- set replaces one element (not a structural modification: iterators stay valid).
- Memory and invalidation
- No allocation.