Skip to lesson

Dynamic arrays: how ArrayList grows

A plain Java array like new int[4] has its length locked the moment it is created. ArrayList feels like a stretchable array, yet under the hood it is built entirely out of ordinary fixed-size arrays plus a clever doubling rule.

Fixed-size arrays versus growable lists: size versus capacity

A dynamic array is an array that grows by itself: when it is full, it creates a bigger array and copies the elements across, as Java's ArrayList does.

A Java array has a fixed size, so you cannot add a fifth element to new int[4]. A dynamic array hides a bigger array and grows it when full. The code below shows size versus capacity.

SizeVsCapacity.javaJava
public class SizeVsCapacity {    public static void main(String[] args) {        int[] data = new int[4]; // capacity: 4 slots, fixed        int size = 0;            // slots actually in use        data[size++] = 72;        data[size++] = 85;        System.out.println("size = " + size + ", capacity = " + data.length);    }}
Output
size = 2, capacity = 4

A dynamic array (such as java.util.ArrayList) solves this by maintaining two numbers alongside an internal fixed-size backing array:

  • capacity (data.length): how many slots the current backing array has allocated in total.
  • size: how many elements the user has actually added so far (0 <= size <= capacity).

A Java array has a fixed size: int[] data = new int[4] makes the JVM reserve a contiguous block of exactly 4 integer slots in memory. You cannot append a 5th element to that block, because the memory right after it may already belong to another object.

As long as size < capacity, appending a new element x simply writes data[size] = x; and increments size++ in O(1) time.

  • size: the number of valid elements currently stored (list.size()).
  • capacity: the length of the hidden backing array (data.length >= size).
  • Unused tail slots (data[size .. capacity - 1]): reserved space waiting for future add calls.

Doubling the capacity and copying when full

What happens when size == capacity and the caller calls add(x)? The dynamic array allocates a new, larger backing array, copies the existing size elements across (Arrays.copyOf(data, newCapacity)), replaces data with the new array, and then places x at data[size++].

Example 1 · Building a working DynamicIntArray from scratch with add, get, set, and removeAt

DynamicIntArrayDemo.javaJava
import java.util.Arrays;
public class DynamicIntArrayDemo {    static class DynamicIntArray {        private int[] data;        private int size;
        DynamicIntArray(int initialCapacity) {            this.data = new int[Math.max(1, initialCapacity)];            this.size = 0;        }
        int size() { return size; }        int capacity() { return data.length; }
        void add(int value) {            if (size == data.length) {                data = Arrays.copyOf(data, data.length * 2);            }            data[size++] = value;        }
        int get(int index) {            checkIndex(index);            return data[index];        }
        int removeAt(int index) {            checkIndex(index);            int removed = data[index];            for (int i = index; i < size - 1; i++) {                data[i] = data[i + 1];            }            size--;            return removed;        }
        private void checkIndex(int index) {            if (index < 0 || index >= size) {                throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);            }        }
        @Override        public String toString() {            return Arrays.toString(Arrays.copyOf(data, size))                + " (size=" + size + ", cap=" + capacity() + ")";        }    }
    public static void main(String[] args) {        DynamicIntArray list = new DynamicIntArray(2);        System.out.println("Start      : " + list);        list.add(10);        list.add(20);        System.out.println("After 2    : " + list);        list.add(30); // Triggers resize 2 -> 4        System.out.println("After 3    : " + list);        list.add(40);        list.add(50); // Triggers resize 4 -> 8        System.out.println("After 5    : " + list);        int removed = list.removeAt(1); // Removes 20 and shifts [30, 40, 50] left        System.out.println("Removed    : " + removed + " -> " + list);    }}
Output
Start      : [] (size=0, cap=2)
After 2    : [10, 20] (size=2, cap=2)
After 3    : [10, 20, 30] (size=3, cap=4)
After 5    : [10, 20, 30, 40, 50] (size=5, cap=8)
Removed    : 20 -> [10, 30, 40, 50] (size=4, cap=8)

What this code does

  • size tracks how many elements are logically present (0 -> 2 -> 3 -> 5 -> 4), while capacity (data.length) only changes when size == data.length (2 -> 4 -> 8).
  • Notice that checkIndex checks index >= size, not index >= data.length, so callers cannot read the unused capacity slots at indices 4..7.

Example 2 · Brute force: grow the array by one slot each time (O(n²) copies in total)

GrowByOneDemo.javaJava
public class GrowByOneDemo {    static long copiesWhenPlusOne(int n) {        int cap = 1;        int size = 0;        long copies = 0;        for (int i = 0; i < n; i++) {            if (size == cap) {                copies += size; // Copy all existing elements into new array of size cap + 1                cap += 1;            }            size++;        }        return copies;    }
    public static void main(String[] args) {        int n = 1025;        System.out.println("Appending n = " + n + " elements:");        System.out.println("  Growing by +1 copies     : " + copiesWhenPlusOne(n) + " (~n^2/2 -> O(n^2) total)");    }}
Output
Appending n = 1025 elements:
  Growing by +1 copies     : 524800 (~n^2/2 -> O(n^2) total)

What this code does

  • When the array grows by one slot, every add after the first full array copies all existing elements.
  • For n = 1,025 appends that is 524,800 copies, which grows like n².

Example 3 · Optimal: double the capacity when full (O(n) copies in total)

DoubleCapacityDemo.javaJava
public class DoubleCapacityDemo {    static long copiesWhenDoubling(int n) {        int cap = 1;        int size = 0;        long copies = 0;        for (int i = 0; i < n; i++) {            if (size == cap) {                copies += size; // Copy all existing elements into new array of size 2 * cap                cap *= 2;            }            size++;        }        return copies;    }
    public static void main(String[] args) {        int n = 1025;        System.out.println("Appending n = " + n + " elements:");        System.out.println("  Doubling capacity copies : " + copiesWhenDoubling(n) + " (< 2n -> O(n) total)");    }}
Output
Appending n = 1025 elements:
  Doubling capacity copies : 2047 (< 2n -> O(n) total)

What this code does

  • Resizes happen only at sizes 1, 2, 4, 8, ... 1024, and together they copy 2,047 elements, fewer than 2n.
  • It is faster because doubling leaves lots of free slots, so most add calls copy nothing and the cost averages to O(1) per add.
  1. Check if (size == data.length) at the start of add(int value).
  2. If full, allocate data = Arrays.copyOf(data, data.length * 2).
  3. Store data[size++] = value.
  4. In get(index) and set(index, val), check if (index < 0 || index >= size) (not data.length!) and throw IndexOutOfBoundsException.

How much bigger should the new array be?

  • Bad idea (capacity + 1): Growing by 1 slot on every add copies 1 + 2 + 3 + … + n = O(n²) elements across n additions!
  • *Good idea (geometric growth — doubling `capacity 2)**: When capacity doubles (1 → 2 → 4 → 8 → 16 → … → n), resize copies happen at powers of 2. The total elements copied across n appends is 1 + 2 + 4 + 8 + … + n < 2n = O(n). Divided across n add calls, the **amortised cost** per append is < 3 operations, or **amortised O(1)**. *(Version & JDK note: in OpenJDK 17, ArrayList starts with a default capacity of 10 on the first add and grows by 1.5x via oldCapacity + (oldCapacity >> 1), which is also geometric growth and gives the same amortised O(1) guarantee; in our custom class we double capacity * 2` for a clean hand trace.)*

Why remove(index) and add(0, x) at the front cost O(n)

Removing from the front of a dynamic array shifts every later element one place left, so it costs O(n), while removing the last element costs O(1). The code below counts the shifts.

  • Removing the last element (remove(size - 1)) shifts 0 elements: O(1).
  • Removing the first element (remove(0)) shifts all n - 1 remaining elements left: O(n).
  • Calling remove(0) inside a loop until an ArrayList is empty takes (n - 1) + (n - 2) + … + 1 = O(n²) time! When you need O(1) removal from the front, use ArrayDeque instead of ArrayList.

Example 4 · Counting shifts in removeAt(0) versus removeAt(size - 1)

RemoveShiftCountDemo.javaJava
public class RemoveShiftCountDemo {    static int countShiftsToRemoveIndex(int size, int index) {        int shifts = 0;        for (int i = index; i < size - 1; i++) {            shifts++;        }        return shifts;    }
    public static void main(String[] args) {        int size = 1000;        System.out.println("Remove last  (index 999) shifts : " + countShiftsToRemoveIndex(size, 999));        System.out.println("Remove middle(index 500) shifts : " + countShiftsToRemoveIndex(size, 500));        System.out.println("Remove front (index 0)   shifts : " + countShiftsToRemoveIndex(size, 0));    }}
Output
Remove last  (index 999) shifts : 0
Remove middle(index 500) shifts : 499
Remove front (index 0)   shifts : 999

What this code does

  • Removing from the end of an ArrayList (list.remove(list.size() - 1)) requires 0 shifts and runs in O(1) time.
  • Removing from index 0 (list.remove(0)) shifts all size - 1 elements one slot left, costing O(n) time.

Because a dynamic array stores elements contiguously in data[0 .. size - 1] with no gaps, removing the element at index requires shifting every element after it (index + 1 through size - 1) one position to the left: for (int i = index; i < size - 1; i++) data[i] = data[i + 1]; and then decrementing size--.

In an Object[]-backed list like ArrayList, remove also sets the vacated slot data[size - 1] = null before decrementing size so the removed object can be garbage-collected.

Next step

Check your understanding

10 quick questions