Skip to lesson

ArrayList vs LinkedList

"ArrayList or LinkedList?" is often the first collections question in a Java interview. The interviewer is checking whether you know how each list works inside, and whether you can avoid the traps around remove and fixed-size lists.

Internals: resizable array vs doubly linked nodes

An ArrayList is a list that keeps its elements in one resizable array. Any element is reached by its index in one step, and when the array is full the list copies everything into a bigger one.

Start with what is inside each list. The program applies the growth rule old + (old >> 1) to show when an attendance list for 100 students resizes.

An ArrayList keeps items in a hidden array. The list names holds Pen, Cup and Bag in a 10-slot array: size 3, capacity 10. When all 10 slots are full, the next add makes a 15-slot array, copies the 10 items and drops the old one.

Example 1 · The 1.5x growth rule for 100 students

GrowthDemo.javaJava
public class GrowthDemo {    public static void main(String[] args) {        int capacity = 10;   // slots made by the first add        int size = 0;        int resizes = 0;
        for (int student = 1; student <= 100; student++) {            if (size == capacity) {                int newCapacity = capacity + (capacity >> 1);                System.out.println("Full at " + size + " -> grow " + capacity + " to " + newCapacity);                capacity = newCapacity;                resizes++;            }            size++;        }        System.out.println("Size " + size + ", capacity " + capacity + ", resizes " + resizes);    }}
Output
Full at 10 -> grow 10 to 15
Full at 15 -> grow 15 to 22
Full at 22 -> grow 22 to 33
Full at 33 -> grow 33 to 49
Full at 49 -> grow 49 to 73
Full at 73 -> grow 73 to 109
Size 100, capacity 109, resizes 6

What this code does

  • This is a simplified model of ArrayList's grow step: capacity >> 1 is half the capacity, so each resize adds 50%.
  • Only 6 copies are needed for 100 adds. Because resizes get rarer, adding at the end costs O(1) on average.
  • If you know the size in advance, new ArrayList<>(100) skips every resize.

An ArrayList stores references in a plain Object[] array. When the array is full, it makes a bigger array, about 1.5 times the old size, and copies everything across. A list made with new ArrayList<>() starts with an empty array and gets 10 slots on the first add (Java 8 and later).

A LinkedList is a doubly linked list: every element sits in a node that also holds a link to the previous and the next node. It never resizes, but each element costs one extra object. It also implements Deque, so it works as a queue or stack. Revise: ArrayList internals (opens in a new tab) and LinkedList (opens in a new tab).

Order of execution

What add does on a full ArrayList

An ArrayList with 10 items in 10 slots gets an 11th item. Put the steps in order.

Interviewers like the follow-up "what is the cost of a resize?" Answer: O(n) for that one copy, but O(1) on average per add, because resizes get rarer as the list grows.

Big-O table for the common operations

Big-O notation describes how the work of an operation grows as the number of elements n grows. O(1) means the same work for any n, and O(n) means the work grows in step with n.

Learn the table in this order: get, add at the end, insert in the middle, remove at the front. The program times get(i) in a loop on both lists.

Example 2 · get(i) in a loop: ArrayList vs LinkedList

GetCostDemo.javaJava
import java.util.ArrayList;import java.util.LinkedList;import java.util.List;
public class GetCostDemo {    static long millisForIndexLoop(List<Integer> list) {        long start = System.nanoTime();        long sum = 0;        for (int i = 0; i < list.size(); i++) {            sum += list.get(i);        }        if (sum < 0) System.out.println("impossible");        return (System.nanoTime() - start) / 1_000_000;    }
    static long millisForEachLoop(List<Integer> list) {        long start = System.nanoTime();        long sum = 0;        for (int value : list) {            sum += value;        }        if (sum < 0) System.out.println("impossible");        return (System.nanoTime() - start) / 1_000_000;    }
    public static void main(String[] args) {        List<Integer> array = new ArrayList<>();        List<Integer> linked = new LinkedList<>();        for (int i = 0; i < 40_000; i++) {            array.add(i);            linked.add(i);        }        System.out.println("ArrayList  get(i) loop: " + millisForIndexLoop(array) + " ms");        System.out.println("LinkedList get(i) loop: " + millisForIndexLoop(linked) + " ms");        System.out.println("LinkedList for-each:    " + millisForEachLoop(linked) + " ms");    }}
Sample output
ArrayList  get(i) loop: 3 ms
LinkedList get(i) loop: 812 ms
LinkedList for-each:    2 ms

What this code does

  • Each linked.get(i) walks up to n/2 nodes, so the index loop is O(n²) on a LinkedList but O(n) on an ArrayList.
  • The for-each loop uses an iterator that moves one node at a time, so it is O(n) for both lists.
  • Interview point: never loop over a List parameter with get(i) if it might be a LinkedList.

The costs, in the order to say them:

  • get(i) / set(i): ArrayList O(1), a direct array index. LinkedList O(n), it walks node by node from the nearer end.
  • add(x) at the end: ArrayList O(1) on average (O(n) only on a resize). LinkedList O(1), it keeps a link to the last node.
  • add(i, x) / remove(i) in the middle: ArrayList O(n), elements shift. LinkedList O(n) to walk to i, then O(1) to relink.
  • remove(0) / addFirst: ArrayList O(n), everything shifts left or right. LinkedList O(1). contains is O(n) for both.
The timing in the example is a sample: your numbers will differ, but the gap between the first two lines will be huge on any computer.

Why ArrayList usually wins in practice

Cache locality means the CPU reads memory in small blocks, so values stored side by side are read much faster than values scattered around memory.

Big-O ties for a middle insert, so speed comes from memory. The program inserts through a ListIterator, the one case where LinkedList clearly wins.

Example 3 · Where LinkedList shines: inserting through a ListIterator

TimetableDemo.javaJava
import java.util.LinkedList;import java.util.List;import java.util.ListIterator;
public class TimetableDemo {    public static void main(String[] args) {        LinkedList<String> day = new LinkedList<>(List.of("Maths", "Physics", "Chemistry", "English"));
        ListIterator<String> it = day.listIterator();        int periods = 0;        while (it.hasNext()) {            it.next();            periods++;            if (periods % 2 == 0 && it.hasNext()) {                it.add("Break");   // O(1): the iterator is already at this spot            }        }        System.out.println(day);
        day.addFirst("Assembly");   // O(1) at the front        day.removeLast();           // O(1) at the back        System.out.println(day);    }}
Output
[Maths, Physics, Break, Chemistry, English]
[Assembly, Maths, Physics, Break, Chemistry]

What this code does

  • it.add links a new node right where the iterator stands, so no elements shift and nothing is walked again.
  • addFirst and removeLast are O(1) because LinkedList keeps links to both ends. On an ArrayList, adding at index 0 shifts every element.

An ArrayList keeps its references side by side. LinkedList nodes are separate objects spread across the heap, so walking them is slow.

That is why ArrayList is the default choice. Even its O(n) middle insert is a single fast block copy (System.arraycopy), which often beats LinkedList's O(n) walk to the position. LinkedList wins only when you are already standing at the position, for example inserting or removing through a ListIterator while you walk the list. For a plain queue or stack, ArrayDeque is usually faster than both.

The collection hierarchy: List vs Set vs Queue vs Map

Collection is the parent interface of List, Set and Queue. It describes a group of single elements that you can add to, remove from and loop over. Map is not a Collection.

Interviewers often ask where each collection sits. The program builds one order list as a List, a Set, a Queue and a Map, and prints each shape.

Example 4 · One order list in four shapes

FourShapesDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Collection;import java.util.List;import java.util.Map;import java.util.Queue;import java.util.Set;import java.util.TreeMap;import java.util.TreeSet;
public class FourShapesDemo {    public static void main(String[] args) {        List<String> orders = new ArrayList<>(List.of("Pen", "Bag", "Pen"));        Set<String> unique = new TreeSet<>(orders);        Queue<String> counter = new ArrayDeque<>(orders);        Map<String, Integer> count = new TreeMap<>();        for (String order : orders) {            count.merge(order, 1, Integer::sum);        }
        System.out.println("List : " + orders);        System.out.println("Set  : " + unique);        System.out.println("Queue: served " + counter.poll() + ", next " + counter.peek());        System.out.println("Map  : " + count);        System.out.println("Is the map a Collection? " + (count instanceof Collection));    }}
Output
List : [Pen, Bag, Pen]
Set  : [Bag, Pen]
Queue: served Pen, next Bag
Map  : {Bag=1, Pen=2}
Is the map a Collection? false

What this code does

  • The list keeps both Pens in order, the set drops the duplicate, and the queue serves the first order first.
  • The map counts orders by key. It prints false for instanceof Collection because Map is a separate hierarchy.

A List keeps insertion order and allows duplicates. A Set rejects duplicates. A Queue hands out elements in a fixed order, usually first in, first out.

Map is the odd one out: it stores key-value pairs and does not extend Collection. Its keySet(), values() and entrySet() give you collection views when you need them. Revise: Collection hierarchy (opens in a new tab).

A one-line diagram to say aloud: Iterable → Collection → List / Set / Queue, and Map on its own.

Traps: remove(int) vs remove(Object), Arrays.asList and List.of

An unmodifiable list cannot be changed after it is created: every change throws UnsupportedOperationException. List.of makes one; Arrays.asList makes a fixed-size list that only allows set.

Three traps decide many marks. The program runs remove(int), Arrays.asList and List.of side by side and prints what each one does.

Example 5 · The three list traps in one program

ListTrapsDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class ListTrapsDemo {    static void tryRun(String label, Runnable action) {        try {            action.run();            System.out.println(label + ": ok");        } catch (RuntimeException e) {            System.out.println(label + ": " + e.getClass().getSimpleName());        }    }
    public static void main(String[] args) {        List<Integer> marks = new ArrayList<>(List.of(10, 20, 30, 40));        marks.remove(1);                    // removes INDEX 1 (the 20)        System.out.println("After remove(1): " + marks);        marks.remove(Integer.valueOf(10));  // removes the VALUE 10        System.out.println("After remove(Integer.valueOf(10)): " + marks);
        List<String> fixed = Arrays.asList("A", "B");        tryRun("asList set", () -> fixed.set(0, "Z"));        tryRun("asList add", () -> fixed.add("C"));
        List<String> frozen = List.of("A", "B");        tryRun("List.of set", () -> frozen.set(0, "Z"));        tryRun("List.of contains(null)", () -> frozen.contains(null));
        List<String> copy = new ArrayList<>(frozen);        copy.add("C");        System.out.println("Copy: " + copy);    }}
Output
After remove(1): [10, 30, 40]
After remove(Integer.valueOf(10)): [30, 40]
asList set: ok
asList add: UnsupportedOperationException
List.of set: UnsupportedOperationException
List.of contains(null): NullPointerException
Copy: [A, B, C]

What this code does

  • With an int argument Java picks remove(int index); with an Integer it picks remove(Object).
  • Arrays.asList is fixed size but writable; List.of is fully unmodifiable and even contains(null) throws.
  • new ArrayList<>(...) makes an independent, growable copy, which is the usual fix.

remove(int index) and remove(Object o) are two different methods. On a List<Integer>, remove(1) removes the element at index 1, not the value 1. Write remove(Integer.valueOf(1)) to remove by value.

Arrays.asList returns a fixed-size list backed by the array: set works, but add and remove throw UnsupportedOperationException. List.of (Java 9+) returns a fully unmodifiable list: even set throws, and it rejects null elements. The fix for both is a copy: new ArrayList<>(...). Revise: Immutable lists (opens in a new tab).

Predict the output

Predict the list trap

Read each snippet and pick what happens.

Round 1 of 3

List<Integer> ids = new ArrayList<>(List.of(10, 20, 30));
ids.remove(10);
System.out.println(ids);

Next step

Check your understanding

12 quick questions