ArrayList vs LinkedList

ArrayList keeps its elements in one array, while LinkedList keeps each one in a separate node linked to its neighbours. That one difference decides memory use and the cost of every operation. This page shows how each list works, measures capacity growth, memory per element and the main operations, and explains the few cases where LinkedList is the better choice.

Contents

Two ways to store a list

ArrayList keeps references to its elements in one Object[] array. Element i is slot i of that array, so get(i) is a single memory read. The array usually has spare slots at the end, and when it is full the list allocates a larger array and copies everything over.

LinkedList is a doubly linked list. Each element lives in its own Node object holding the element and references to the previous and next nodes; the list remembers only the first and last node. Reaching element i means following links from whichever end is closer, one node at a time. In exchange, adding or removing at a node you already hold only changes a few links.

The two lists compared
PropertyArrayListLinkedList
SinceJava 1.2Java 1.2
StorageOne contiguous array of referencesOne node object per element
Memory per elementOne reference, plus spare capacityA 24-byte node (with compressed references)
Marker and extra interfacesRandomAccessDeque
get(i), set(i, x)O(1)O(n)
add(x) at the endO(1) amortizedO(1)
add(0, x), remove(0)O(n), shifts every elementO(1)
add(i, x) in the middleO(n), shifts halfO(n), walks half
Insert or remove through an iteratorO(n)O(1)
Best forAlmost every listMany edits at the ends or at an iterator position

Memory layout matters more than the table suggests. CPUs read memory in 64-byte cache lines, so walking an array whose slots sit side by side is fast, while walking nodes scattered across the heap costs a separate memory access per element. The programs below ran on JDK 21.

How ArrayList grows

An array cannot change size, so add sometimes has to allocate a new one. The program reads the length of the private array through reflection after every one of 1,000 additions, which needs --add-opens java.base/java.util=ALL-UNNAMED. Production code should never do this; here it shows the real growth policy.

Java
import java.lang.reflect.Field;
import java.util.ArrayList;

public class GrowthRule {

    // Reads ArrayList's private array; needs --add-opens java.base/java.util=ALL-UNNAMED
    static int capacity(ArrayList<?> list) throws ReflectiveOperationException {
        Field f = ArrayList.class.getDeclaredField("elementData");
        f.setAccessible(true);
        return ((Object[]) f.get(list)).length;
    }

    public static void main(String[] args) throws ReflectiveOperationException {
        ArrayList<Integer> list = new ArrayList<>();
        System.out.println("new ArrayList<>(): capacity " + capacity(list) + " (no array yet)");

        StringBuilder sizes = new StringBuilder();
        long copies = 0;
        int last = 0;
        for (int i = 0; i < 1000; i++) {
            list.add(i);
            int cap = capacity(list);
            if (cap != last) {
                copies += last;                    // every existing element moves
                sizes.append(sizes.isEmpty() ? "" : ", ").append(cap);
                last = cap;
            }
        }
        System.out.println("capacities while adding 1,000: " + sizes);
        System.out.println("elements copied while growing: " + copies);

        list.clear();
        System.out.println("after clear(): size " + list.size() + ", capacity " + capacity(list));
        list.trimToSize();
        System.out.println("after trimToSize(): capacity " + capacity(list));

        ArrayList<Integer> sized = new ArrayList<>(1000);
        System.out.println("new ArrayList<>(1000): capacity " + capacity(sized));
    }
}

Output:

Output
new ArrayList<>(): capacity 0 (no array yet)
capacities while adding 1,000: 10, 15, 22, 33, 49, 73, 109, 163, 244, 366, 549, 823, 1234
elements copied while growing: 2456
after clear(): size 0, capacity 1234
after trimToSize(): capacity 0
new ArrayList<>(1000): capacity 1000
  • A new ArrayList has no array at all, capacity 0. The first add creates one with room for 10.
  • Each time it is full, the capacity grows by half: 10, 15, 22, 33 and so on, reaching 1,234 for 1,000 elements.
  • Growing copied 2,456 elements in total, about 2.5 per element added. Because each step grows by a fixed fraction, that ratio stays bounded however many elements are added, which is why add at the end is O(1) amortized.
  • clear() keeps the large array, so a cleared list still holds 1,234 slots. trimToSize() releases them.
  • new ArrayList<>(1000) allocates the right size immediately, so no copying happens at all.

Memory per element

To compare the structures alone, the program creates a million Integer objects once and adds the same objects to each collection, so only the collection's own memory is counted.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.function.Supplier;

public class MemoryCost {

    public static void main(String[] args) {
        int n = 1000000;
        Integer[] values = new Integer[n];
        for (int i = 0; i < n; i++) {
            values[i] = i;                        // created once, shared by every collection
        }
        measure("ArrayList (grown)", n, values, ArrayList::new);
        measure("ArrayList (presized)", n, values, () -> new ArrayList<>(n));
        measure("LinkedList", n, values, LinkedList::new);
        measure("ArrayDeque", n, values, ArrayDeque::new);
        long before = used();
        int[] primitives = new int[n];
        long after = used();
        System.out.printf("%-22s %5.1f bytes per element (%d)%n", "int[]",
            (double) (after - before) / n, primitives.length);
    }

    static void measure(String name, int n, Integer[] values,
            Supplier<Collection<Integer>> factory) {
        long before = used();
        Collection<Integer> c = factory.get();
        for (Integer v : values) {
            c.add(v);
        }
        long after = used();
        System.out.printf("%-22s %5.1f bytes per element (%d)%n", name,
            (double) (after - before) / n, c.size());
    }

    static long used() {
        Runtime rt = Runtime.getRuntime();
        for (int i = 0; i < 3; i++) {
            System.gc();
        }
        return rt.totalMemory() - rt.freeMemory();
    }
}

Output (heap measurements are approximate):

Output
ArrayList (grown)        5.2 bytes per element (1000000)
ArrayList (presized)     4.2 bytes per element (1000000)
LinkedList              24.0 bytes per element (1000000)
ArrayDeque               5.2 bytes per element (1000000)
int[]                    4.2 bytes per element (1000000)
  • A presized ArrayList costs about 4 bytes per element: one compressed reference, the same as an int[]. Grown one element at a time, it used about 5 bytes, because of spare capacity after the last growth step.
  • LinkedList costs 24 bytes per element: each node has a 12-byte header and three 4-byte references (item, next, previous), rounded up to 24. That is five to six times the ArrayList cost.
  • ArrayDeque is array-based like ArrayList and costs about the same.
  • All of these hold references to Integer objects of 16 bytes each, which are not counted here. A list of numbers is far smaller as an int[], or with a primitive collection library.

Reading by index: the LinkedList trap

The most common LinkedList mistake is a loop with get(i). The program times that loop and a for-each loop on lists of 10,000, 20,000 and 40,000 elements, doubling each time so the growth rate is visible. Each value is the fastest of three runs.

Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.ToLongFunction;

public class AccessCost {

    static long byIndex(List<Integer> list) {
        long sum = 0;
        for (int i = 0; i < list.size(); i++) {
            sum += list.get(i);              // ArrayList: one array read. LinkedList: a walk.
        }
        return sum;
    }

    static long forEach(List<Integer> list) {
        long sum = 0;
        for (int value : list) {             // uses the list's own iterator
            sum += value;
        }
        return sum;
    }

    public static void main(String[] args) {
        for (int n : new int[] {10000, 20000, 40000}) {
            List<Integer> array = new ArrayList<>();
            List<Integer> linked = new LinkedList<>();
            for (int i = 0; i < n; i++) {
                array.add(i);
                linked.add(i);
            }
            System.out.printf("n=%,6d  get(i): ArrayList %6.2f ms, LinkedList %7.1f ms"
                + "  | for-each: ArrayList %5.2f ms, LinkedList %5.2f ms%n", n,
                best(array, AccessCost::byIndex), best(linked, AccessCost::byIndex),
                best(array, AccessCost::forEach), best(linked, AccessCost::forEach));
        }
    }

    // Best of 3 runs, in milliseconds
    static double best(List<Integer> list, ToLongFunction<List<Integer>> f) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            if (f.applyAsLong(list) < 0) {
                throw new AssertionError();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best / 1e6;
    }
}

Output (rough timings, 2-CPU Linux machine, JDK 21):

Output
n=10,000  get(i): ArrayList   0.30 ms, LinkedList    34.8 ms  | for-each: ArrayList  0.30 ms, LinkedList  0.40 ms
n=20,000  get(i): ArrayList   0.62 ms, LinkedList   134.9 ms  | for-each: ArrayList  0.23 ms, LinkedList  0.27 ms
n=40,000  get(i): ArrayList   0.24 ms, LinkedList   537.7 ms  | for-each: ArrayList  0.22 ms, LinkedList  0.38 ms
  • On ArrayList, the index loop stayed around a millisecond. On LinkedList it took hundreds of times longer, and every doubling of n made it about four times slower: each get(i) walks up to n/2 nodes, so the loop does about n2/4 steps.
  • The for-each loop uses the list's iterator, which moves one link per step, so LinkedList was as fast as ArrayList at these sizes.
  • Code that receives an unknown List can test list instanceof RandomAccess before choosing an index loop. ArrayList implements that marker interface and LinkedList does not. The looping page compares all the loop styles.

Adding and removing: where each list wins

The program times six editing patterns on lists of 100,000 elements, each on a fresh list and the fastest of three runs. They are chosen to cover the ends, the middle, and edits made through an iterator.

Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.function.Supplier;

public class EditSpeed {

    public static void main(String[] args) {
        int n = 100000;
        System.out.printf("%-34s %10s %10s%n", "operation", "ArrayList", "LinkedList");
        row("add 100,000 at the end", () -> new ArrayList<>(), () -> new LinkedList<>(), list -> {
            for (int i = 0; i < n; i++) {
                list.add(i);
            }
        }, 0);
        row("add 100,000 at index 0", () -> new ArrayList<>(), () -> new LinkedList<>(), list -> {
            for (int i = 0; i < n; i++) {
                list.add(0, i);
            }
        }, 0);
        row("remove(0) until empty", ArrayList::new, LinkedList::new, list -> {
            while (!list.isEmpty()) {
                list.remove(0);
            }
        }, n);
        row("iterator insert after each even", ArrayList::new, LinkedList::new, list -> {
            ListIterator<Integer> it = list.listIterator();
            while (it.hasNext()) {
                if (it.next() % 2 == 0) {
                    it.add(-1);
                }
            }
        }, n);
        row("removeIf(odd)", ArrayList::new, LinkedList::new,
            list -> list.removeIf(x -> x % 2 != 0), n);
        row("add 1,000 at index size/2", ArrayList::new, LinkedList::new, list -> {
            for (int i = 0; i < 1000; i++) {
                list.add(list.size() / 2, i);
            }
        }, n);
    }

    interface Work {
        void run(List<Integer> list);
    }

    static void row(String name, Supplier<List<Integer>> a, Supplier<List<Integer>> l, Work w,
            int prefill) {
        System.out.printf("%-34s %8.1f ms %8.1f ms%n", name, best(a, w, prefill),
            best(l, w, prefill));
    }

    // Best of 3 runs on a fresh list each time, in milliseconds
    static double best(Supplier<List<Integer>> factory, Work w, int prefill) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            List<Integer> list = factory.get();
            for (int i = 0; i < prefill; i++) {
                list.add(i);
            }
            long t0 = System.nanoTime();
            w.run(list);
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best / 1e6;
    }
}

Output (rough timings, 2-CPU Linux machine, JDK 21):

Output
operation                           ArrayList LinkedList
add 100,000 at the end                  0.7 ms      0.7 ms
add 100,000 at index 0                361.4 ms      3.9 ms
remove(0) until empty                 355.2 ms      0.6 ms
iterator insert after each even       185.0 ms      4.9 ms
removeIf(odd)                           1.5 ms      1.7 ms
add 1,000 at index size/2               3.4 ms     89.3 ms
  • Adding at the end costs about the same for both.
  • Adding at index 0 or removing index 0 repeatedly made ArrayList shift every element each time, and it was around a hundred times slower than LinkedList, which only relinks the first node. For queue-like use at the front, ArrayDeque is better than both.
  • Inserting through a ListIterator after every even number is where LinkedList shines: each insert is a constant-time relink, while ArrayList shifts the rest of the array 50,000 times.
  • removeIf was equally fast for both. ArrayList implements it in a single pass that compacts the array, so bulk removal is not a reason to choose LinkedList; see removing elements from a list.
  • Inserting at size/2 by index is O(n) for both, but ArrayList was much faster: shifting half an array is one fast System.arraycopy, while LinkedList must walk 50,000 scattered nodes to find the spot.

Editing while walking the list

The same ListIterator code works on both lists. The program inserts a marker after every multiple of three in one pass, then shows the catch of index-based insertion on a LinkedList.

Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class MiddleEdits {

    // Insert "x" after every element that is a multiple of 3, in one pass.
    static void insertAfterMultiplesOfThree(List<String> list) {
        ListIterator<String> it = list.listIterator();
        while (it.hasNext()) {
            int value = Integer.parseInt(it.next());
            if (value % 3 == 0) {
                it.add("x");   // LinkedList: relink two nodes. ArrayList: shift the rest right.
            }
        }
    }

    public static void main(String[] args) {
        List<String> array = new ArrayList<>(List.of("1", "2", "3", "4", "5", "6"));
        List<String> linked = new LinkedList<>(array);

        insertAfterMultiplesOfThree(array);
        insertAfterMultiplesOfThree(linked);

        System.out.println("ArrayList:  " + array);
        System.out.println("LinkedList: " + linked);

        // The catch: reaching the middle by index is still a walk for LinkedList
        linked.add(linked.size() / 2, "mid");
        System.out.println("add(size/2): " + linked);
    }
}

Output:

Output
ArrayList:  [1, 2, 3, x, 4, 5, 6, x]
LinkedList: [1, 2, 3, x, 4, 5, 6, x]
add(size/2): [1, 2, 3, x, mid, 4, 5, 6, x]

Both lists give the same result, since the code only uses the List interface. Only the cost differs: with k insertions into a list of n elements, ArrayList moves about k × n elements and LinkedList makes k relinks. The last line is the catch: add(size/2, x) still has to walk to the middle, so it is O(n) for LinkedList too. Iterator and ListIterator are compared on the iterator page.

First and last elements: SequencedCollection in Java 21

Getting the last element of an ArrayList used to mean list.get(list.size() - 1), while LinkedList had getLast() from Deque. Java 21 (JEP 431) gave every List the same methods. The program uses them on both lists and on an empty one.

Java
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class SequencedOps {

    public static void main(String[] args) {
        List<String> array = new ArrayList<>(List.of("a", "b", "c"));
        LinkedList<String> linked = new LinkedList<>(array);

        // Java 21 (JEP 431): every List is a SequencedCollection
        array.addFirst("start");
        array.addLast("end");
        System.out.println("ArrayList:  " + array + " first=" + array.getFirst()
            + " last=" + array.getLast());
        System.out.println("reversed view: " + array.reversed());
        array.removeFirst();
        System.out.println("after removeFirst: " + array);

        // LinkedList has had these since Java 6 through Deque
        linked.addFirst("start");
        linked.addLast("end");
        System.out.println("LinkedList: " + linked + " peekLast=" + linked.peekLast());

        // getFirst on an empty list throws; peekFirst (Deque only) returns null
        List<String> empty = new ArrayList<>();
        try {
            empty.getFirst();
        } catch (java.util.NoSuchElementException e) {
            System.out.println("empty ArrayList getFirst(): NoSuchElementException");
        }
        System.out.println("empty LinkedList peekFirst(): " + new LinkedList<String>().peekFirst());
    }
}

Output:

Output
ArrayList:  [start, a, b, c, end] first=start last=end
reversed view: [end, c, b, a, start]
after removeFirst: [a, b, c, end]
LinkedList: [start, a, b, c, end] peekLast=end
empty ArrayList getFirst(): NoSuchElementException
empty LinkedList peekFirst(): null
  • addFirst, addLast, getFirst, getLast, removeFirst and removeLast now work on an ArrayList, with the same costs as the index operations: the First versions shift the array.
  • reversed() returns a view in reverse order without copying, so iterating backwards no longer needs an index loop or a ListIterator.
  • getFirst() on an empty list throws NoSuchElementException. The Deque methods peekFirst and peekLast, which return null instead, exist only on LinkedList and ArrayDeque.

Queues and stacks: use ArrayDeque

LinkedList implements Deque, so it is often used as a queue or a stack. ArrayDeque does the same job with a circular array and no node per element. The program also shows how the two handle null.

Java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;

public class QueueChoice {

    public static void main(String[] args) {
        // LinkedList implements Deque, so it can be used as a queue or a stack...
        Queue<String> linkedQueue = new LinkedList<>();
        linkedQueue.offer("a");
        linkedQueue.offer(null);              // ...and it accepts null, which hides bugs
        System.out.println("LinkedList queue: " + linkedQueue + ", poll() = "
                + linkedQueue.poll() + ", then poll() = " + linkedQueue.poll());

        // ArrayDeque is the usual choice: an array that wraps around, no node per element
        Deque<String> deque = new ArrayDeque<>();
        deque.offerLast("a");
        deque.offerLast("b");
        deque.offerFirst("front");
        System.out.println("ArrayDeque: " + deque + ", pollFirst() = " + deque.pollFirst());
        try {
            deque.offer(null);
        } catch (NullPointerException e) {
            System.out.println("ArrayDeque rejects null: NullPointerException");
        }
    }
}

Output:

Output
LinkedList queue: [a, null], poll() = a, then poll() = null
ArrayDeque: [front, a, b], pollFirst() = front
ArrayDeque rejects null: NullPointerException

LinkedList accepts null, which is a trap for queues: poll() returns null both for "the element was null" and for "the queue is empty". ArrayDeque rejects null with NullPointerException. Its documentation says it is likely to be faster than LinkedList when used as a queue. More options are on the Queue and Deque page.

Which one to choose

Choosing a list
You needUse
A general-purpose listArrayList
A list whose size you knownew ArrayList<>(expectedSize)
A queue, stack or double-ended queueArrayDeque
A list that never changesList.of(...); see immutable collections
Many inserts and removals at an iterator position on a large listLinkedList, after measuring
A list shared between threadsCopyOnWriteArrayList or a synchronized wrapper
Millions of numbersAn int[] or long[]

Declare variables with the interface type, List<String> names = new ArrayList<>(), so switching later is a one-word change. If you expect LinkedList to be faster for your case, measure with real data, ideally with JMH; it usually is not.