java.util · java.base · since Java 1.2

ArrayList

declaration
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, Serializable

The default List: growable array, O(1) index access, amortized O(1) append, cache-friendly iteration. Presize when the size is known.

  • Grows ~1.5× on overflow; middle insert/remove shifts elements (O(n))
  • Not synchronized — confine, wrap, or use concurrent alternatives across threads

Key methods

ArrayList(int initialCapacity)Presize to skip regrowth copies.
ArrayList(Collection<? extends E> c)Copy-construct from any collection.
E get(int index) / E set(int index, E element)O(1) array read/overwrite — no shifting.
boolean add(E e)Append at the end — amortized O(1), occasionally O(n) on regrowth.
void add(int index, E element)Positional insert — O(n), shifts every following element right.
E remove(int index)Positional remove — O(n), shifts every following element left.
boolean contains(Object o) / int indexOf(Object o)Linear scan via equals() — O(n); reach for a HashSet if this is hot.
boolean removeIf(Predicate<? super E>)Single-pass bulk removal — avoids the O(n²) repeated-remove(int) trap.
void forEach(Consumer<? super E>)Index-order traversal without an explicit Iterator.
List<E> subList(int from, int to)Write-through range view backed by the same array.
Iterator<E> iterator()Fail-fast — throws ConcurrentModificationException on structural change mid-iteration.
void ensureCapacity(int)Pre-grow before a bulk add.
void trimToSize()Release slack after shrinking.

Example

Java
ArrayList<String> ids = new ArrayList<>(expectedCount); // presize — no regrowth copies
for (String line : source) ids.add(line);
ids.trimToSize(); // release slack once loading is done and the list is stable
Presize to the known count, bulk-load, then trim once the list is stable.