ArrayList<E> · Java
remove(int) / remove(Object)
Removes by position or by value (first equal element); both shift the rest left.
public E remove(int index); public boolean remove(Object o)
Complexity
| Best case | O(1) for the last index |
|---|---|
| Worst case | O(n) |
| Extra space | O(1) |
remove(int) shifts size − index − 1 references. remove(Object) also scans to find the element first.
Tested example
List<Integer> list = new ArrayList<>(List.of(5, 6, 7, 8));
int removed = list.remove(0); // remove(int index): shifts the rest left
assert removed == 5;
list.remove(Integer.valueOf(8)); // remove(Object): a different overload!
assert list.equals(List.of(6, 7));
Parameters
- index / o
- A position, or a value compared with equals().
Behaviour
- Returns
- remove(int): the removed element. remove(Object): whether something was removed.
- Errors and preconditions
- remove(int): IndexOutOfBoundsException for a bad index.
- Changes
- size decreases by 1; the vacated slot is nulled.
- Memory and invalidation
- Does not shrink the array.