How ArrayList works inside
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)An ArrayList is a plain array with some smart bookkeeping. Inside it there is an ordinary array and a count of how many slots are in use. Knowing this tells you which list operations are fast and which are slow.
An array inside the list
The size of an ArrayList is the number of items really in it. Its capacity is the length of the hidden array inside, which is how many items fit before the list must grow. The size is never more than the capacity.
Every ArrayList keeps its items in an ordinary Java array, the backing array, plus an int called size. The array's length is the capacity: how many items fit before the array must grow.
ArrayList<String> names = new ArrayList<>(10); // capacity 10, size 0names.add("Asha");names.add("Ravi");names.add("Meena");System.out.println(names.size()); // 3names.get(1); // O(1): straight to slot 1names.get(5); // IndexOutOfBoundsException: Index 5 out of bounds for length 3A list with size 3 and capacity 10 has 7 spare slots at the end. Those slots are not part of the list. get(5) checks against size, not capacity, so it throws IndexOutOfBoundsException.
get(i) and set(i, x) go straight to slot i of the array, just like arr[i]. Their cost does not depend on the list size: O(1), constant time.
How the list grows
Amortized O(1) means constant time on average. A few calls are slow, but the slow ones are so rare that, spread over many calls, each call costs a fixed small amount.
new ArrayList<>() starts with an empty array. The first add creates room for 10 items. When the array is full, the next add makes a new array about 1.5 times as big and copies every item across.
Example 1 · A mini ArrayList: size, capacity and growth
class MiniList { private String[] data = new String[0]; private int size = 0;
void add(String item) { if (size == data.length) { grow(); } data[size] = item; size++; }
private void grow() { int oldCapacity = data.length; int newCapacity = oldCapacity == 0 ? 10 : oldCapacity + oldCapacity / 2; String[] bigger = new String[newCapacity]; for (int i = 0; i < size; i++) { bigger[i] = data[i]; } data = bigger; System.out.println(" grow: " + oldCapacity + " -> " + newCapacity + " (copied " + size + ")"); }
String get(int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index " + index + " out of bounds for length " + size); } return data[index]; }
int size() { return size; }
int capacity() { return data.length; }}
public class MiniListDemo { public static void main(String[] args) { MiniList tokens = new MiniList(); for (int i = 1; i <= 16; i++) { if (i == 1 || i == 11 || i == 16) { System.out.println("Adding token " + i); } tokens.add("T" + i); } System.out.println("Size " + tokens.size() + ", capacity " + tokens.capacity()); System.out.println("Last token: " + tokens.get(15));
try { tokens.get(20); } catch (IndexOutOfBoundsException e) { System.out.println("get(20): " + e.getMessage()); } }}Adding token 1 grow: 0 -> 10 (copied 0) Adding token 11 grow: 10 -> 15 (copied 10) Adding token 16 grow: 15 -> 22 (copied 15) Size 16, capacity 22 Last token: T16 get(20): Index 20 out of bounds for length 16
What this code does
- The array grows only on the 1st, 11th and 16th add. Every other add just writes into a free slot.
- Each growth copies all current items: 0, then 10, then 15. This is the slow part of a rare add.
- Slot 20 exists in the array (capacity 22), but the list has only 16 items, so
get(20)is refused, just like the realArrayList.
Example 2 · Counting copies: why growth stays cheap
public class GrowthCostDemo { static long copiesFor(int items, boolean growByHalf) { long copies = 0; int capacity = 10; for (int size = 0; size < items; size++) { if (size == capacity) { copies = copies + size; if (growByHalf) { capacity = capacity + capacity / 2; } else { capacity = capacity + 10; } } } return copies; }
public static void main(String[] args) { int items = 1_000_000;
long half = copiesFor(items, true); long ten = copiesFor(items, false);
System.out.println("Adding " + items + " items"); System.out.println("Grow by half: " + half + " copies, " + (half / items) + " per add on average"); System.out.println("Grow by 10: " + ten + " copies, " + (ten / items) + " per add on average"); }}Adding 1000000 items Grow by half: 2430972 copies, 2 per add on average Grow by 10: 49999500000 copies, 49999 per add on average
What this code does
- The program only counts copies; it does not build arrays. Growing by half copies about 2 items per add on average: constant, no matter how many items.
- Growing by a fixed 10 slots would copy about 50,000 items per add for a million items. That is why
ArrayListgrows by a fraction, not by a fixed amount.
The new capacity is the old capacity plus half of it, so capacities go 10, 15, 22, 33, 49 and so on. That one add is slow because it copies everything. But growth is rare, and each growth makes room for many more adds. Spread over all adds, the copying is only about two copies per item, so add at the end is amortized O(1).
These exact numbers are how the standard JDK (OpenJDK 17) does it. The Java rules only promise that add at the end is cheap on average.
Order of execution
What add does when the array is full
Tap the steps in the order the list does them.
new ArrayList<>(50_000) creates the array at that size once, and no growth happens on the way.Why the front is slow
An array has no gaps. To insert at index 0, every item must first move one slot to the right. To remove index 0, every later item moves one slot to the left.
Example 3 · Insert at the front vs add at the end
class MiniIntList { private int[] data = new int[2000]; private int size = 0; long moves = 0;
void addAt(int index, int value) { for (int i = size; i > index; i--) { data[i] = data[i - 1]; moves++; } data[index] = value; size++; }
int get(int index) { return data[index]; }}
public class ShiftCostDemo { public static void main(String[] args) { MiniIntList atEnd = new MiniIntList(); MiniIntList atFront = new MiniIntList();
for (int i = 1; i <= 1000; i++) { atEnd.addAt(i - 1, i); atFront.addAt(0, i); }
System.out.println("1000 adds at the end: " + atEnd.moves + " moves"); System.out.println("1000 adds at the front: " + atFront.moves + " moves"); System.out.println("First items: " + atEnd.get(0) + " and " + atFront.get(0)); }}1000 adds at the end: 0 moves 1000 adds at the front: 499500 moves First items: 1 and 1000
What this code does
- Adding at the end (
index == size) moves nothing. Adding at index 0 first moves every existing item one slot right. - For the front, the moves are 0 + 1 + 2 + ... + 999 = 499,500. Doubling the items would roughly quadruple that: this is O(n) per insert, O(n²) for the whole job.
- The capacity is fixed at 2000 here so that only shifting is counted.
Example 4 · The same cost in a real ArrayList
import java.util.ArrayList;import java.util.List;
public class FrontVsEndTiming { public static void main(String[] args) { int n = 100_000;
long start = System.nanoTime(); List<Integer> end = new ArrayList<>(); for (int i = 0; i < n; i++) { end.add(i); } long endMs = (System.nanoTime() - start) / 1_000_000;
start = System.nanoTime(); List<Integer> front = new ArrayList<>(); for (int i = 0; i < n; i++) { front.add(0, i); } long frontMs = (System.nanoTime() - start) / 1_000_000;
System.out.println("add at end: " + endMs + " ms"); System.out.println("add at front: " + frontMs + " ms"); System.out.println("Same size? " + (end.size() == front.size())); }}add at end: 9 ms add at front: 625 ms Same size? true
What this code does
System.nanoTime()reads a timer; the difference divided by 1,000,000 gives milliseconds. Your numbers will differ, but the gap will be large.- Both lists end up with 1 lakh items. The front version is far slower only because every insert shifts all items already there.
With 1 lakh items, that is 1 lakh moves for a single call. So the cost of add(i, x) and remove(i) grows with the number of items after i: O(n). At the end, nothing moves, so adding or removing the last item is cheap. The same idea explains searching: contains and indexOf may check every item, so they are O(n) too.
The cost of each call on an ArrayList:
get(i),set(i, x)→ O(1)add(x)at the end,remove(size() - 1)→ O(1) (add is amortized)add(i, x),remove(i)near the front → O(n), items shiftcontains,indexOf,remove(Object)→ O(n), linear search
Capacity tools: initial capacity and trimToSize
new ArrayList<>(n) sets the starting capacity. The list is still empty: size 0, no items, not n nulls. A negative n throws IllegalArgumentException.
Example 5 · Capacity is not size
import java.util.ArrayList;import java.util.List;
public class CapacityDemo { public static void main(String[] args) { ArrayList<String> results = new ArrayList<>(500); System.out.println("Size: " + results.size() + ", empty: " + results.isEmpty());
try { results.get(0); } catch (IndexOutOfBoundsException e) { System.out.println("get(0): " + e.getMessage()); }
results.add("Pass"); results.add("Fail"); results.trimToSize(); System.out.println("After trimToSize: " + results);
try { List<String> bad = new ArrayList<>(-1); } catch (IllegalArgumentException e) { System.out.println("Negative capacity: " + e.getMessage()); } }}Size: 0, empty: true get(0): Index 0 out of bounds for length 0 After trimToSize: [Pass, Fail] Negative capacity: Illegal Capacity: -1
What this code does
- Room for 500 items, but size 0: the list is empty and
get(0)fails with length 0. trimToSize()belongs to theArrayListclass, not theListinterface, so this variable is typedArrayList. It shrinks the hidden array; the items stay the same.- A negative capacity makes no sense, so the constructor throws
IllegalArgumentException.
ensureCapacity(n) grows the array once to at least n, before a big batch of adds. trimToSize() shrinks the array to exactly size, giving spare memory back when the list will not grow again.
These are tuning tools. For most lists the default growth is fast enough; reach for them when you know the counts or have measured a problem.
Next step
Check your understanding
12 quick questions