ArrayList in Java

Everything you need to know about ArrayList in Java: internal resizable array, time complexities, capacity management, and interview essentials.

ArrayList<E> is the most commonly used collection class in Java. It implements the List interface using a resizable array (sometimes called a dynamic array) as its backing store. When the array fills up, ArrayList allocates a new, larger array and copies elements into it. In exchange for that occasional resize cost, you get O(1) random access by index — making ArrayList the right default choice for most ordered-collection needs.

Internal Structure

Internally, ArrayList holds a single Object[] called elementData, along with an int size field that tracks how many elements have been added. The array is often larger than size — the difference is the unused capacity reserved for future growth.

Growth Policy

When add is called and size == elementData.length, ArrayList grows the array. The default growth factor is roughly 1.5× (the new capacity is oldCapacity + (oldCapacity >> 1)). Creating an ArrayList without arguments starts with capacity 10; the first add that would exceed the current capacity triggers a resize.

Time Complexities

Operation Complexity Notes
get(i) O(1) Direct array index lookup
set(i, e) O(1) Direct array write
add(e) (at end) Amortized O(1) O(n) on rare resize
add(i, e) (at index) O(n) Must shift elements right
remove(i) (at index) O(n) Must shift elements left
remove(Object o) O(n) Linear scan + shift
contains(o) O(n) Linear scan
size() O(1) Field read
clear() O(n) Must null out references

Example 1: Core Operations

import java.util.ArrayList;
import java.util.List;

public class ArrayListBasics {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>();

        // Adding elements
        cities.add("London");
        cities.add("Tokyo");
        cities.add("Paris");
        cities.add(1, "Berlin"); // insert at index 1
        System.out.println(cities); // [London, Berlin, Tokyo, Paris]

        // Accessing by index
        System.out.println(cities.get(2)); // Tokyo

        // Updating
        cities.set(0, "New York");
        System.out.println(cities); // [New York, Berlin, Tokyo, Paris]

        // Removing
        cities.remove("Berlin");             // by value
        cities.remove(cities.size() - 1);   // by index (last element)
        System.out.println(cities);          // [New York, Tokyo]

        // Size and containment
        System.out.println(cities.size());         // 2
        System.out.println(cities.contains("Tokyo")); // true
    }
}

Example 2: Capacity Management and Iteration

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListAdvanced {
    public static void main(String[] args) {
        // Pre-size capacity to avoid repeated resizing when count is known
        List<Integer> numbers = new ArrayList<>(1000);
        for (int i = 1; i <= 10; i++) {
            numbers.add(i * i); // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
        }

        // Sort descending
        numbers.sort(Collections.reverseOrder());
        System.out.println(numbers); // [100, 81, 64, 49, 36, 25, 16, 9, 4, 1]

        // removeIf — safe way to remove during "iteration"
        numbers.removeIf(n -> n > 50);
        System.out.println(numbers); // [36, 25, 16, 9, 4, 1]

        // Trim to actual size to release unused backing-array memory
        ((ArrayList<Integer>) numbers).trimToSize();

        // Convert to immutable snapshot
        List<Integer> snapshot = List.copyOf(numbers);
        System.out.println(snapshot); // [36, 25, 16, 9, 4, 1]
    }
}

Common Mistakes

  • Removing an integer value from List<Integer> using remove(int). list.remove(3) removes the element at index 3, not the value 3. Use list.remove(Integer.valueOf(3)) to remove by value.
  • Calling add or remove inside a for-each loop. This throws ConcurrentModificationException. Use list.removeIf(predicate), an explicit Iterator, or collect changes outside the loop.
  • Using ArrayList when Arrays.asList(...) returns a fixed-size list. The returned list supports set but not add/remove. Wrap it in new ArrayList<>(Arrays.asList(...)) if you need a fully mutable list.
  • Ignoring capacity for performance-sensitive code. Creating an ArrayList for millions of elements without a capacity hint will trigger many resizes. Pass the expected size to the constructor: new ArrayList<>(estimatedSize).
  • Holding a reference to the backing array after toArray(). list.toArray() returns a plain Object[]. Modifying that array does not affect the list, and modifying the list after calling toArray() does not affect the returned array. The two are independent snapshots.

Best Practices

  • Always declare the variable type as List<E>, not ArrayList<E>, to keep implementation details hidden from callers.
  • Provide an initial capacity estimate when you know the approximate final size: new ArrayList<>(capacity).
  • Prefer list.sort(Comparator) over Collections.sort(list) — both work, but the instance method reads more naturally in modern Java.
  • Call trimToSize() on long-lived lists after a bulk-population phase to release the unused tail of the backing array.
  • Use List.copyOf(list) (Java 10+) to create an immutable snapshot rather than wrapping with Collections.unmodifiableList, which still reflects mutations to the original.

Interview Questions

1. How does ArrayList resize itself internally?

When add is called and there is no remaining capacity, ArrayList allocates a new array of size (oldCapacity + (oldCapacity >> 1)) — approximately 1.5× the current size. It then copies all existing elements into the new array using Arrays.copyOf. The cost of a single resize is O(n), but averaged over many insertions the amortized cost per add is O(1).

2. What is the default initial capacity of ArrayList?

The default initial capacity is 10, but the backing array is only allocated on the first add (the no-arg constructor stores an empty shared array). If you pass a capacity to the constructor, e.g. new ArrayList<>(50), the backing array is allocated immediately with that size.

3. What is the difference between size() and capacity in ArrayList?

size() is the number of elements currently stored. Capacity is the total length of the backing array, including unused slots. ArrayList does not expose capacity publicly — you can see it via ensureCapacity and trimToSize, but there is no capacity() getter in the public API.

4. When is ArrayList a poor choice?

ArrayList performs poorly for frequent insertions or deletions in the middle of a large list, because each operation requires O(n) element shifts. It also performs poorly for concurrent writes without external synchronisation. For frequent end-only additions and removals, ArrayDeque is often a better choice than LinkedList or ArrayList.

5. How do you safely iterate and remove elements from an ArrayList?

Use list.removeIf(predicate) (Java 8+), which is the cleanest option. Alternatively, use an explicit Iterator<E> it = list.iterator() and call it.remove() after it.next(). A third option is to iterate in reverse by index: for (int i = list.size()-1; i >= 0; i--) { if (condition) list.remove(i); }.

6. Is ArrayList thread-safe?

No. ArrayList is not synchronised. Concurrent reads are safe, but concurrent reads and writes, or concurrent writes, can produce inconsistent state or throw ConcurrentModificationException. Use Collections.synchronizedList(new ArrayList<>()) for a synchronised wrapper, or CopyOnWriteArrayList for read-heavy concurrent scenarios.

7. How does ArrayList compare to an array?

An array has a fixed length set at creation; ArrayList grows dynamically. Arrays can hold primitives directly (e.g. int[]); ArrayList only holds objects (boxed types for primitives). Arrays support element assignment in O(1); so does ArrayList.set. For raw performance with a fixed size, a plain array is faster. For flexibility, ArrayList is preferred.

Summary

  • ArrayList implements List using a resizable array with O(1) random access and amortized O(1) append.
  • add/remove in the middle of the list is O(n) due to element shifting.
  • Pre-sizing with new ArrayList<>(capacity) avoids repeated resize copies.
  • Always declare as List<E> in variable and parameter types, not ArrayList<E>.
  • Use removeIf for safe conditional removal and trimToSize() to release unused memory.

Continue Learning

Previous: List | Next: LinkedList

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.