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
ArrayListObject[]iiget(i)
LinkedListNodei
| Property | ArrayList | LinkedList |
|---|---|---|
| Since | Java 1.2 | Java 1.2 |
| Storage | One contiguous array of references | One node object per element |
| Memory per element | One reference, plus spare capacity | A 24-byte node (with compressed references) |
| Marker and extra interfaces | RandomAccess | Deque |
get(i)set(i, x) | O(1) | O(n) |
add(x) | O(1) amortized | O(1) |
add(0, x)remove(0) | O(n), shifts every element | O(1) |
add(i, x) | O(n), shifts half | O(n), walks half |
| Insert or remove through an iterator | O(n) | O(1) |
| Best for | Almost every list | Many 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--add-opens java.base/java.util=ALL-UNNAMED
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:
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
has no array at all, capacity 0. The firstArrayList creates one with room for 10.add - 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
at the end is O(1) amortized.add keeps the large array, so a cleared list still holds 1,234 slots.clear() releases them.trimToSize() allocates the right size immediately, so no copying happens at all.new ArrayList<>(1000)
Memory per element
To compare the structures alone, the program creates a million Integer
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):
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
costs about 4 bytes per element: one compressed reference, the same as anArrayList . Grown one element at a time, it used about 5 bytes, because of spare capacity after the last growth step.int[] 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 theLinkedList cost.ArrayList is array-based likeArrayDeque and costs about the same.ArrayList- All of these hold references to
objects of 16 bytes each, which are not counted here. A list of numbers is far smaller as anInteger , or with a primitive collection library.int[]
Reading by index: the LinkedList trap
The most common LinkedListget(i)
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):
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
, the index loop stayed around a millisecond. OnArrayList it took hundreds of times longer, and every doubling of n made it about four times slower: eachLinkedList walks up to n/2 nodes, so the loop does about n2/4 steps.get(i) - The for-each loop uses the list's iterator, which moves one link per step, so
was as fast asLinkedList at these sizes.ArrayList - Code that receives an unknown
can testList before choosing an index loop.list instanceof RandomAccess implements that marker interface andArrayList does not. TheLinkedListlooping 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.
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):
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
shift every element each time, and it was around a hundred times slower thanArrayList , which only relinks the first node. For queue-like use at the front,LinkedList is better than both.ArrayDeque - Inserting through a
after every even number is whereListIterator shines: each insert is a constant-time relink, whileLinkedList shifts the rest of the array 50,000 times.ArrayList was equally fast for both.removeIf implements it in a single pass that compacts the array, so bulk removal is not a reason to chooseArrayList ; seeLinkedListremoving elements from a list .- Inserting at
by index is O(n) for both, butsize/2 was much faster: shifting half an array is one fastArrayList , whileSystem.arraycopy must walk 50,000 scattered nodes to find the spot.LinkedList
Editing while walking the list
The same ListIteratorLinkedList
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:
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 ListArrayListLinkedListadd(size/2, x)LinkedListIteratorListIterator
First and last elements: SequencedCollection in Java 21
Getting the last element of an ArrayListlist.get(list.size() - 1)LinkedListgetLast()DequeList
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:
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 andremoveFirst now work on anremoveLast , with the same costs as the index operations: theArrayList versions shift the array.First returns a view in reverse order without copying, so iterating backwards no longer needs an index loop or areversed() .ListIterator on an empty list throwsgetFirst() . TheNoSuchElementException methodsDeque andpeekFirst , which returnpeekLast instead, exist only onnull andLinkedList .ArrayDeque
Queues and stacks: use ArrayDeque
LinkedListDequeArrayDequenull
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:
LinkedList queue: [a, null], poll() = a, then poll() = null
ArrayDeque: [front, a, b], pollFirst() = front
ArrayDeque rejects null: NullPointerException
LinkedListnullpoll()nullArrayDequenullNullPointerExceptionLinkedList
Which one to choose
| You need | Use |
|---|---|
| A general-purpose list | ArrayList |
| A list whose size you know | new ArrayList<>(expectedSize) |
| A queue, stack or double-ended queue | ArrayDeque |
| A list that never changes | List.of(...) |
| Many inserts and removals at an iterator position on a large list | LinkedList |
| A list shared between threads | |
| Millions of numbers | An int[]long[] |
Declare variables with the interface type, List<String> names = new ArrayList<>()LinkedList