- Prerequisites
- 4.1 Collection Architecture
- Covers
- ArrayList · LinkedList · CopyOnWriteArrayList
- Related
- 5.2 ArrayList Internals · 6.1 Iterator (fail-fast) · B2V4 concurrent collections
On this page
1Concept / Definition
Three general-purpose List implementations cover almost all needs: ArrayList, backed by a resizable array and the default choice; LinkedList, a doubly linked list that also implements Deque; and CopyOnWriteArrayList, a thread-safe list that copies its array on every write, designed for read-mostly concurrent use.

2Why It Exists
Before Java 1.2 the only growable list was Vector, which synchronised every method whether or not the list was shared. The Collections Framework separated the contract, List, from the storage, so that different workloads could choose different trade-offs behind the same interface: an array for fast indexing, linked nodes for cheap changes at a known position, and, from Java 5, a copy-on-write array for lists that many threads read and few change.
The three exist because no single structure is best for all three access patterns. In practice the array wins far more often than Big-O tables suggest, which is why this topic recommends ArrayList by default and treats the other two as special cases that must be justified.
3Core Concepts
ArrayList
Stores references in an Object[] that grows by about 50% when full (5.2). Indexed access is O(1) and iteration is fast and cache-friendly because references are contiguous. Adding at the end is amortised O(1); inserting or removing in the middle shifts elements, O(n), though the shift is a fast System.arraycopy. Not thread-safe; iterators are fail-fast. In practice ArrayList is the right List in the vast majority of cases.
LinkedList
Each element lives in a separate Node object with prev and next links. Adding or removing at either end is O(1), and removal through an iterator is O(1) once positioned. But get(i) walks the list, O(n), and every node costs an extra object of about 24 bytes plus pointer chasing that defeats CPU caches. Benchmarks show ArrayList (or ArrayDeque for queue use) is faster for nearly all realistic workloads; LinkedList is rarely the best choice.
CopyOnWriteArrayList
A thread-safe list in java.util.concurrent. Every mutation takes a lock, copies the underlying array, modifies the copy and publishes it with a volatile write. Reads and iteration never lock and never throw ConcurrentModificationException: an iterator sees the snapshot that existed when it was created. Writes cost O(n) time and memory, so it suits small collections that are read far more often than written — listener lists, configuration, routing tables.


4How It Works Internally
ArrayList keeps an Object[] and a size; add writes the next slot and grows the array by half when it is full, and add(i, e) or remove(i) move the tail with System.arraycopy (5.2). LinkedList keeps first, last and size, and each element sits in a Node with item, prev and next fields. get(i) walks from whichever end is nearer, so it costs up to n/2 steps, and add(i, e) has to make the same walk before it can link the new node (Figure 4).

CopyOnWriteArrayList holds a volatile Object[]. A write takes a lock, copies the array with the change applied and publishes the new array with one volatile write; a read just loads the current array, so readers never block and always see a complete array. Its iterator keeps a reference to the array that was current when the iterator was created. That is why it never throws ConcurrentModificationException, and also why iterator().remove() is not supported.
ArrayList and LinkedList instead have fail-fast iterators. Every structural change increments a modCount field; the iterator records the value when it is created and compares it on each next(). The check is a best-effort bug detector, not a guarantee: when a removal makes hasNext() return false first, the loop simply ends early, and the remaining elements are skipped without an exception (Example 2).
5APIs / Features / Syntax
All three implement the whole List interface, but the cost of the same call differs. The table gives the operations that decide the choice; the Java 21 SequencedCollection methods are available on all three:
| Operation | ArrayList | LinkedList | CopyOnWriteArrayList |
|---|---|---|---|
| get(i), set(i, e) | O(1) | O(n): walks from the nearer end | O(1); set copies the array |
| add(e), addLast(e) | amortised O(1) | O(1), allocates a node | O(n): copies the array |
| add(0, e), addFirst(e) | O(n) shift | O(1) | O(n) copy |
| remove(i), remove(o) | O(n) shift | O(n) walk, O(1) unlink | O(n) copy |
| getFirst(), getLast(), reversed() | O(1) | O(1) | O(1) |
| iterator | fail-fast | fail-fast; ListIterator add/remove O(1) | snapshot, no remove |
| removeIf(p), replaceAll(f) | O(n), one pass | O(n), one pass | O(n), one copy |
Two related factories are not general-purpose lists. Arrays.asList(array) returns a fixed-size list that writes through to the array, and List.of(...) returns an immutable list (7.1). Collections.synchronizedList(list) wraps any list with a lock on each call, but iteration still needs synchronized (list) { ... } around the loop.
6Practical Examples
Example 1 — Choosing a List by usage
Problem. A service holds orders in a list, filters out cancelled ones, queues work items and notifies listeners on every event. Each use has a different best list, or no list at all.
// Default: ArrayList, with a capacity hint when the size is known
List<Order> orders = new ArrayList<>(expectedCount);
// Removing while iterating: removeIf, not remove(i) inside a for-each
orders.removeIf(o -> o.status() == Status.CANCELLED);
// Queue-like use: prefer ArrayDeque over LinkedList
Deque<Task> work = new ArrayDeque<>();
// Read-mostly, concurrently accessed listeners
private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();
public void subscribe(OrderListener l) { listeners.add(l); } // rare
public void publish(OrderEvent e) {
for (OrderListener l : listeners) l.on(e); // frequent, lock-free
}Why it works. The capacity hint avoids repeated growth when the count is known; removeIf removes in one pass instead of shifting the tail once per removal; a queue belongs in a Deque; and a listener list that is read on every event and changed only at start-up is the textbook case for copy-on-write.
Example 2 — Mini program: a listener registry that changes while it publishes
Problem. A one-shot listener unsubscribes itself while an event is being delivered. With an ArrayList behind the registry there is no exception, yet one listener misses the event. The same registry runs twice, once on each list.
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
public class ListenerRegistry {
private final List<Consumer<String>> listeners;
ListenerRegistry(List<Consumer<String>> store) { this.listeners = store; }
void subscribe(Consumer<String> l) { listeners.add(l); }
void unsubscribe(Consumer<String> l) { listeners.remove(l); }
void publish(String event) {
for (Consumer<String> l : listeners) l.accept(event);
}
static void run(String name, List<Consumer<String>> store) {
ListenerRegistry bus = new ListenerRegistry(store);
List<String> log = new ArrayList<>();
bus.subscribe(e -> log.add("audit:" + e));
bus.subscribe(new Consumer<>() { // a one-shot listener
public void accept(String e) {
log.add("once:" + e);
bus.unsubscribe(this); // changes the list mid-publish
}
});
bus.subscribe(e -> log.add("mail:" + e));
try {
bus.publish("e1");
bus.publish("e2");
System.out.println(name + " -> " + log);
} catch (ConcurrentModificationException ex) {
System.out.println(name + " -> CME after " + log);
}
}
public static void main(String[] args) {
run("ArrayList ", new ArrayList<>());
run("CopyOnWriteArrayList", new CopyOnWriteArrayList<>());
}
}ArrayList -> [audit:e1, once:e1, audit:e2, mail:e2]
CopyOnWriteArrayList -> [audit:e1, once:e1, mail:e1, audit:e2, mail:e2]
Why it behaves this way. In the ArrayList run, the one-shot listener is removed while the iterator stands at index 2 of a list that now has size 2, so hasNext() is false and the loop ends: mail never sees e1, and no exception reports it (Figure 5). The CopyOnWriteArrayList loop iterates a snapshot, so all three listeners see e1, and the next publish reads the new array without the one-shot listener. With a fourth listener the ArrayList run would instead fail with ConcurrentModificationException, which is the better outcome: the silent skip is the dangerous one.
Example 3 — Removing elements while walking a list
Problem. Remove the void orders from a list. Three of the four obvious loops look correct, and only two of them are.
import java.util.*;
public class RemoveWhileIterating {
static List<String> orders() {
return new ArrayList<>(
List.of("ok-1", "void-2", "void-3", "ok-4", "void-5"));
}
public static void main(String[] args) {
List<String> a = orders();
for (int i = 0; i < a.size(); i++) { // index loop
if (a.get(i).startsWith("void")) a.remove(i);
}
System.out.println("index loop : " + a);
List<String> b = orders();
try {
for (String s : b) { // for-each loop
if (s.startsWith("void")) b.remove(s);
}
} catch (ConcurrentModificationException e) {
System.out.println("for-each : CME, list now " + b);
}
List<String> c = orders();
boolean changed = c.removeIf(s -> s.startsWith("void"));
System.out.println("removeIf : " + c + " (changed=" + changed + ")");
List<String> d = orders();
for (Iterator<String> it = d.iterator(); it.hasNext(); ) {
if (it.next().startsWith("void")) it.remove();
}
System.out.println("iterator : " + d);
}
}index loop : [ok-1, void-3, ok-4]
for-each : CME, list now [ok-1, void-3, ok-4, void-5]
removeIf : [ok-1, ok-4] (changed=true)
iterator : [ok-1, ok-4]Why it behaves this way. The index loop removes void-2 at index 1, the tail shifts left and void-3 moves into index 1, which the loop has already passed, so it survives. The for-each loop removes through the list, not the iterator, so the next next() sees the changed modCount and throws. removeIf and Iterator.remove are correct; on an ArrayList, removeIf is also O(n) overall, because it compacts the array once instead of shifting it after every removal.
Example 4 — Middle insertion: is LinkedList really faster?
Problem. A code review proposes LinkedList because the code "inserts a lot in the middle". Measure it. The program inserts 20,000 elements at the middle of each list and then reads them back by index; the first round only warms up the JIT.
import java.util.*;
public class MiddleInsertCost {
static long insertMiddle(List<Integer> list, int n) {
long t0 = System.nanoTime();
for (int i = 0; i < n; i++) list.add(list.size() / 2, i);
return (System.nanoTime() - t0) / 1_000_000;
}
static long readByIndex(List<Integer> list) {
long t0 = System.nanoTime(), sum = 0;
for (int i = 0; i < list.size(); i++) sum += list.get(i);
if (sum < 0) System.out.println(); // keep the loop alive
return (System.nanoTime() - t0) / 1_000_000;
}
public static void main(String[] args) {
int n = 20_000;
for (int round = 0; round < 2; round++) { // round 0 warms up
List<Integer> array = new ArrayList<>(), linked = new LinkedList<>();
long ai = insertMiddle(array, n), li = insertMiddle(linked, n);
long ar = readByIndex(array), lr = readByIndex(linked);
if (round == 1) {
System.out.printf("insert in middle: ArrayList %d ms, "
+ "LinkedList %d ms%n", ai, li);
System.out.printf("get(i) loop : ArrayList %d ms, "
+ "LinkedList %d ms%n", ar, lr);
System.out.println("same contents : " + array.equals(linked));
}
}
}
}insert in middle: ArrayList 3 ms, LinkedList 137 ms
get(i) loop : ArrayList 0 ms, LinkedList 139 ms
same contents : trueWhy it behaves this way. Both inserts are O(n) per call, but they do different work. The ArrayList moves a contiguous block of references with one arraycopy, which the CPU does at memory bandwidth; the LinkedList follows up to 10,000 next pointers to scattered nodes, with a cache miss at almost every step, before it does its O(1) link. The get(i) loop shows the second cost: O(1) per call for the array, O(n) for the linked list, so the whole loop is O(n²). The exact numbers vary by machine; for decisions, measure with JMH.
7Common Problems & Mistakes
| Mistake | Consequence | Better approach |
|---|---|---|
| LinkedList chosen for "frequent insertions" | Reaching the position is an O(n) pointer walk with cache misses; the insert is rarely the cost (Example 4) | ArrayList, or ArrayDeque when inserts are at the ends; measure before switching |
| list.get(i) in a loop over a LinkedList | Each get walks from an end, so the loop is O(n²); fine in tests, slow with production sizes | Use for-each or an iterator, or an ArrayList |
| CopyOnWriteArrayList for frequently modified or large lists | Every write copies the whole array: O(n) time and garbage per write, memory spikes under load | ArrayList confined to one thread, or a concurrent queue or map for shared write-heavy data |
| Collections.synchronizedList iterated without holding its lock | Each call is synchronised, the loop is not: another thread's add causes CME or a missed element | synchronized (list) { for (...) } around the whole loop, or CopyOnWriteArrayList |
| Arrays.asList treated as a fully mutable list | add and remove throw UnsupportedOperationException; set writes into the original array | new ArrayList<>(Arrays.asList(...)) when the list must grow |
| Removing by index in a forward loop | The shifted neighbour is skipped without an error (Example 3) | removeIf, or Iterator.remove |
8Performance & Production Considerations
For large lists, pre-size ArrayList when the final size is known to avoid repeated copying, and call trimToSize() on long-lived lists that have finished growing. Memory per element: about 4 bytes (compressed reference) for ArrayList versus about 24 bytes of node overhead for LinkedList, in both cases plus the element objects themselves. CopyOnWriteArrayList doubles memory transiently on each write.
9Architecture & Design Considerations
Declare List in APIs and choose ArrayList by default. Reach for CopyOnWriteArrayList only for shared, read-mostly data; for shared, write-heavy data, reconsider the design (queues, concurrent maps, or confinement to one thread). Avoid LinkedList unless measurements show a benefit.
10Interview Questions & Answers
What is the difference between ArrayList and LinkedList?
ArrayList uses a resizable array: O(1) indexed access, amortised O(1) append, O(n) middle insertion. LinkedList uses doubly linked nodes: O(1) insertion and removal at the ends or at an iterator position, O(n) indexed access, and much higher memory per element.
When would you use LinkedList?
Rarely. Possibly when you frequently add or remove through a ListIterator in the middle of a long list and never index. For queue or stack use, ArrayDeque is better; for general lists, ArrayList.
How does CopyOnWriteArrayList achieve thread safety?
Mutations lock, copy the array, modify the copy and publish it via a volatile reference. Readers use whatever array they see without locking, and iterators work on an immutable snapshot, so they never throw ConcurrentModificationException.
Why is ArrayList usually faster than LinkedList even for insertions?
Reaching the insertion point in a LinkedList is O(n) pointer chasing with poor cache locality, while ArrayList's element shift is a highly optimised contiguous memory copy. Node allocation also adds GC work.
What are the risks of using CopyOnWriteArrayList for a list of active sessions updated on every login?
Every login copies the whole array — O(n) time and garbage per write — and memory spikes under load. Iterators also see stale snapshots. A ConcurrentHashMap-based set is more appropriate for write-heavy shared data.
How would you choose list implementations in a high-throughput service?
Default to ArrayList with capacity hints; keep lists confined to one thread where possible; use CopyOnWriteArrayList only for small read-mostly shared lists such as listeners; use queues rather than lists for producer–consumer flows; and validate choices with allocation and latency profiling.
What does Arrays.asList return, and how does it differ from new ArrayList<>(...)?
A fixed-size list backed by the array: set writes into the array, and add or remove throw UnsupportedOperationException. new ArrayList<>(Arrays.asList(...)) copies the elements into a growable list that is independent of the array. For a read-only list of constants, List.of(...) is clearer, because it is fully immutable and rejects null.
What does this program print?
import java.util.*;
public class RemoveQuiz {
public static void main(String[] args) {
List<Integer> ids = new ArrayList<>(List.of(3, 1, 2));
ids.remove(1);
System.out.println(ids);
ids.remove(Integer.valueOf(3));
System.out.println(ids);
String[] codes = {"a", "b", "c"};
List<String> view = Arrays.asList(codes);
view.set(0, "z");
System.out.println(codes[0]);
try {
view.add("d");
} catch (UnsupportedOperationException e) {
System.out.println("add: " + e.getClass().getSimpleName());
}
}
}It prints [3, 2], then [2], then z, then add: UnsupportedOperationException. ids.remove(1) with an int argument chooses remove(int index), so it removes the element at index 1, the value 1. remove(Integer.valueOf(3)) chooses remove(Object) and removes the value 3. Arrays.asList writes through to the array, so codes[0] becomes z, and the fixed-size list rejects add.
What does this program print?
import java.util.*;
public class SubListQuiz {
public static void main(String[] args) {
List<String> all = new ArrayList<>(List.of("a", "b", "c", "d"));
List<String> firstTwo = all.subList(0, 2);
firstTwo.set(0, "A");
System.out.println(all);
all.add("e");
try {
System.out.println(firstTwo);
} catch (ConcurrentModificationException e) {
System.out.println("ConcurrentModificationException");
}
}
}It prints [A, b, c, d] and then ConcurrentModificationException. subList returns a view over the same array, so set through the view changes all. Adding to all is a structural change the view did not make; the view compares its expected modCount with the list's on its next use, here inside toString, and throws. A sub-list is valid only until the backing list is structurally modified; copy it with new ArrayList<>(all.subList(0, 2)) if it must outlive changes.
A loop removes a listener from an ArrayList while iterating over it, and no exception is thrown. Is the code safe?
No. The fail-fast check runs in next(), but hasNext() only compares the cursor with the current size. When the removal leaves the cursor equal to the new size, the loop ends quietly and the last element is skipped (Example 2). The absence of ConcurrentModificationException proves nothing; use removeIf, Iterator.remove, or a copy-on-write list when listeners may change during delivery.
Under load, a service logs occasional ConcurrentModificationException from a shared ArrayList of subscribers, and some notifications are lost. How do you fix it?
The list is mutated by one thread while another iterates it. ArrayList is not thread-safe, so besides the visible exceptions there may be invisible damage: lost adds and stale reads. If subscriptions are rare and notifications frequent, switch to CopyOnWriteArrayList: iteration needs no lock and sees a consistent snapshot. If subscriptions change often, protect the list with one lock for both mutation and iteration, or hand events to a queue consumed by one thread. Add a concurrent test that subscribes while publishing.
Why must you hold the lock while iterating a Collections.synchronizedList?
The wrapper synchronises each method call on the list, but a loop is many calls: iterator(), then hasNext() and next() repeatedly. Between two of them another thread can add or remove an element, and the fail-fast iterator throws or skips. Holding synchronized (list) around the whole loop makes the iteration atomic with respect to other callers, at the price of blocking writers for its whole duration.
For a shared list of 50 routing rules, read on every request and replaced a few times a day, would you use CopyOnWriteArrayList, a synchronized list or an immutable list in a volatile field?
A synchronised list makes every request take a lock, which is the wrong cost for a read-mostly list. CopyOnWriteArrayList gives lock-free reads, and each write copies only 50 references. Because the rules are replaced as a whole, an immutable List.copyOf(...) held in a volatile field, or an AtomicReference, is simpler still: readers get a consistent set of rules, and an update is one reference swap instead of many individual writes. I would choose the volatile immutable list and keep CopyOnWriteArrayList for element-by-element changes such as listener registration.
What List-related guidelines would you put into a platform's coding standards?
List in signatures and ArrayList as the default implementation, pre-sized when the size is known; LinkedList only with a benchmark that justifies it, and ArrayDeque for queues and stacks; immutable lists (List.copyOf, toList()) at API boundaries; CopyOnWriteArrayList only for small, read-mostly shared lists; and no shared mutable ArrayList without a documented lock. Back the rules with static analysis, and with allocation profiles of the hot paths.
A batch job that used to take 2 minutes now takes 40 after a refactoring replaced ArrayList with List<...> = new LinkedList<>() in a data-loading layer. How do you confirm and fix the regression?
A profile will most likely show the time inside LinkedList.node(int), the walk behind get(i), called from indexed loops that were O(n) in total on an ArrayList and are O(n²) on a linked list (Example 4). Confirm with a CPU profile or a JFR recording, then either restore ArrayList or rewrite the loops to use iterators. To prevent a recurrence, add a performance test with production-sized data to the pipeline, since the change was correct in every functional test.
Test your knowledge on this topic →Try multiple choice →Flashcards from this topic's 15 questions, filtered by level and type.
Key Takeaways
- ArrayList is the default: fast indexing and iteration.
- LinkedList is rarely the best choice; use ArrayDeque for queues and stacks.
- CopyOnWriteArrayList: lock-free snapshot reads, O(n) writes — read-mostly shared data only.