Code Snippets
/

ArrayList vs LinkedList Cheat Sheet

ArrayList vs LinkedList Cheat Sheet

`ArrayList` and `LinkedList` both implement `List`, but their performance profiles are nearly opposite. This snippet shows the basic operations on each, the cases where `LinkedList` actually wins (head/tail mutation via the `Deque` API), and a quick benchmark that demonstrates random access cost. The takeaway: default to `ArrayList`; only reach for `LinkedList` when you genuinely need queue or deque behaviour.

Java
Easy
3 snippets
java-collections
data-structures
comparison

346 views

8

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        list.add(1, "x");         // inserts shift the tail; O(n)
        System.out.println(list); // [a, x, b, c]
        System.out.println("size=" + list.size());
        System.out.println("get(2)=" + list.get(2)); // O(1) random access
        list.remove("x");
        System.out.println("after remove: " + list);
    }
}

ArrayList is a resizing array: add(E) is amortised O(1), get(i) is O(1), and iteration is cache-friendly because elements are contiguous in memory. add(i, E) and remove(i) are O(n) because the tail must shift, but you rarely insert in the middle, so this is not a real bottleneck. Use ArrayList for almost everything: returning collections from methods, building up results in a loop, accumulating filtered values. The default capacity is 10 but it doubles on demand, so pre-sizing with new ArrayList<>(expected) saves reallocations only on hot paths.