Java LinkedList vs ArrayList: Linked Lists, ListIterator and Array Lists
How Java's LinkedList and ArrayList work inside, when each one wins, and how to use ListIterator to add, set and remove while you walk a list. Covers fail-fast iterators, ConcurrentModificationException, the get(i) loop trap, and why Vector is obsolete.
kvi5hnuCode Sprout team member13 min readOn this page
ArrayList and LinkedList both implement List, so code written against the interface works with either. Their performance is very different, though, because one stores elements in an array and the other in a chain of linked nodes. This article opens up both classes, shows how a list iterator lets you edit a list while you walk through it, and ends with a practical rule for choosing between them. Spoiler: the answer is ArrayList far more often than textbooks suggest.
The problem with removing from the middle of an array
Arrays and ArrayList share a weakness. Removing an element from the middle means every element after it must move one slot toward the front. Inserting in the middle is the same problem in the other direction. For a list of a million elements, one removal near the front shifts almost a million references.

A linked list avoids the shifting. Each element lives in its own node, and the node holds references to its neighbours. In Java, every linked list is doubly linked, so each node knows both its successor (next) and its predecessor (prev). To remove a node you update two links: the predecessor's next and the successor's prev. Nothing else moves.
The catch is in the phrase "once you are at the node". A linked list has no fast way to find position 500,000. You have to walk there link by link. Linked lists win only when you are already walking through the list with an iterator and edit as you go.
LinkedList with a plain Iterator
The simplest use looks like any other collection:
var staff = new LinkedList<String>();
staff.add("Ava");
staff.add("Ben");
staff.add("Cleo");
Iterator<String> it = staff.iterator();
String first = it.next(); // visit first element
String second = it.next(); // visit second element
it.remove(); // remove the last visited element: Ben
LinkedList.add appends to the end. The interesting part is removal through the iterator, which is cheap because the iterator already holds a reference to the node it just passed.
ListIterator: editing a list while you walk it
A plain Iterator can only remove. A linked list is an ordered collection, though, so it makes sense to insert at the current position too. That is what the ListIterator subinterface adds. Every List provides one through listIterator().
interface ListIterator<E> extends Iterator<E> {
void add(E element);
void set(E element);
E previous();
boolean hasPrevious();
int nextIndex();
int previousIndex();
// plus hasNext, next, remove from Iterator
}
Notice that add returns void, unlike Collection.add, which returns boolean. An insertion into a list always changes the list, so there is nothing to report.
The cursor sits between elements
The key mental model is that a list iterator's position is between elements, never on one. A list with n elements has n + 1 positions. For A B C they are |ABC, A|BC, AB|C and ABC|.

next()jumps right over one element and returns it.previous()jumps left over one element and returns it.add(e)inserts before the cursor. The cursor ends up after the new element, so callingaddseveral times inserts the elements in the order you supply them.listIterator(n)returns an iterator positioned just before index n, so the firstnext()returnsget(n).nextIndex()is the index of the element the nextnext()would return.previousIndex()is the index for the nextprevious(), which is always one less.
To insert "Jade" after the first element:
ListIterator<String> iter = staff.listIterator();
iter.next(); // skip past the first element
iter.add("Jade");
listIterator(size()) starts at the far end, which is handy for walking a list backwards with hasPrevious() and previous().
remove and set depend on the last move
Iterator.remove deletes the element that the last next() or previous() jumped over. That makes its direction depend on how you got there:
- After
next(), the removed element is the one to the left of the cursor. - After
previous(), it is the one to the right.
You cannot call remove twice in a row. You also cannot call it right after add, because no element has been "just visited". Both cases throw IllegalStateException.
set(e) follows the same rule. It replaces the element returned by the last next() or previous():
ListIterator<String> li = letters.listIterator();
String oldValue = li.next(); // returns the first element
li.set(oldValue.toUpperCase()); // replaces it
Fail-fast iterators and ConcurrentModificationException
Suppose two iterators walk the same list and one of them removes an element. The other iterator might now hold a reference to a node that no longer exists, or point at the wrong index. Java's collection iterators detect this and fail loudly instead of returning garbage:
List<String> list = ...;
ListIterator<String> iter1 = list.listIterator();
ListIterator<String> iter2 = list.listIterator();
iter1.next();
iter1.remove();
iter2.next(); // throws ConcurrentModificationException
The mechanism is simple. The collection keeps a modification count (modCount in the JDK source) that goes up on every structural change, meaning any change that adds or removes elements. Each iterator remembers the count it was created with, plus its own changes. Before every operation it compares the two and throws ConcurrentModificationException on a mismatch.
Two details matter in practice:
setis not a structural change. Replacing an element doesn't change the list's shape, so several iterators can all callsetwithout tripping the check. The demo below does exactly that.- The check is best effort. The specification only promises that iterators try to fail fast. Don't write code that relies on the exception.
The safe rule: attach as many read-only iterators to a collection as you like, or exactly one iterator that both reads and writes.
The word "concurrent" here does not mean threads. A single thread triggers it easily. Thread-safe collections are a separate topic in the concurrency part of this course.
Random access in a linked list: the get(i) trap
LinkedList implements List, so it has get(int), set(int, E), add(int, E) and remove(int). These methods work, but each one walks the chain from an end to reach the index. The JDK starts from whichever end is closer (from the tail if the index is at least size() / 2), but that is still O(n) per call.
So this innocent-looking loop is a performance disaster on a linked list:
for (int i = 0; i < list.size(); i++)
process(list.get(i)); // O(n) each time: O(n²) in total for LinkedList
Every get(i) restarts the walk, because a linked list doesn't cache positions. Use a for-each loop or an iterator, which is O(1) per step for every list type. LinkedList deliberately does not implement the RandomAccess marker interface, so generic algorithms can detect this and avoid index loops.
A complete example
The program below runs every operation from this article: removal through an iterator, add at the cursor, the four insertion spots, walking backwards, set and remove after previous, concurrent modification (including the silent for-each bug), and merging two lists. The merge loop inserts each element of b after an element of a. Then it removes every second element of b and uses the bulk operation removeAll.
import java.util.*;
public class Solution {
public static void main(String[] args) {
// 1. Iterator.remove on a linked list
var staff = new LinkedList<String>();
staff.add("Ava");
staff.add("Ben");
staff.add("Cleo");
Iterator<String> it = staff.iterator();
String first = it.next(); // visit first element
String second = it.next(); // visit second element
it.remove(); // remove last visited element (Ben)
System.out.println("visited " + first + ", " + second + " -> " + staff);
// 2. ListIterator.add inserts before the iterator position
staff = new LinkedList<>(List.of("Ava", "Ben", "Cleo"));
ListIterator<String> iter = staff.listIterator();
iter.next(); // skip past first element
iter.add("Jade");
iter.add("Kai"); // several adds go in the order given
System.out.println("after add: " + staff + ", nextIndex " + iter.nextIndex() + ", previousIndex " + iter.previousIndex());
// the n + 1 insertion spots of a three-element list
for (int pos = 0; pos <= 3; pos++) {
var abc = new LinkedList<>(List.of("A", "B", "C"));
ListIterator<String> li = abc.listIterator(pos); // iterator just before index pos
li.add("x");
System.out.print(String.join("", abc) + " ");
}
System.out.println();
// 3. walking backwards, set, and remove after previous()
var letters = new LinkedList<>(List.of("a", "b", "c", "d"));
ListIterator<String> back = letters.listIterator(letters.size());
var reversed = new StringBuilder();
while (back.hasPrevious()) reversed.append(back.previous());
System.out.println("backwards: " + reversed);
ListIterator<String> li = letters.listIterator();
String oldValue = li.next();
li.set(oldValue.toUpperCase()); // replace the element returned by next
li.next();
li.next(); // now between c and d
li.previous(); // jumps back over c
li.remove(); // removes c: the element to the RIGHT this time
System.out.println("after set and remove: " + letters);
// 4. concurrent modification detection
List<String> list = new LinkedList<>(List.of("p", "q", "r"));
ListIterator<String> iter1 = list.listIterator();
ListIterator<String> iter2 = list.listIterator();
iter1.next();
iter1.remove();
try {
iter2.next();
} catch (ConcurrentModificationException e) {
System.out.println("iter2.next(): ConcurrentModificationException");
}
list = new LinkedList<>(List.of("p", "q", "r"));
try {
for (String s : list) if (s.equals("p")) list.remove(s); // DON'T
} catch (ConcurrentModificationException e) {
System.out.println("remove p inside for each: ConcurrentModificationException");
}
list = new LinkedList<>(List.of("p", "q", "r"));
for (String s : list) if (s.equals("q")) list.remove(s); // still wrong...
System.out.println("remove q inside for each: no exception, " + list + " (r was never visited)");
list.removeIf(s -> s.equals("p")); // the right way
System.out.println("removeIf: " + list);
// set is not a structural modification: several writers are fine
list = new LinkedList<>(List.of("p", "q", "r"));
ListIterator<String> w1 = list.listIterator(), w2 = list.listIterator();
w1.next(); w1.set("P");
w2.next(); w2.set("PP");
System.out.println("two iterators calling set: " + list);
// 5. merge two lists, then remove every second element (trace the iterators!)
var a = new LinkedList<>(List.of("Ann", "Cid", "Eve"));
var b = new LinkedList<>(List.of("Ben", "Dot", "Fay", "Gus"));
ListIterator<String> aIter = a.listIterator();
Iterator<String> bIter = b.iterator();
while (bIter.hasNext()) {
if (aIter.hasNext()) aIter.next();
aIter.add(bIter.next());
}
System.out.println("merged: " + a);
bIter = b.iterator();
while (bIter.hasNext()) {
bIter.next(); // skip one element
if (bIter.hasNext()) {
bIter.next(); // skip next element
bIter.remove(); // remove that element
}
}
System.out.println("every second removed from b: " + b);
a.removeAll(b); // bulk operation
System.out.println("a without b's elements: " + a);
// 6. List methods with indexes, and deque-style methods of LinkedList
var words = new LinkedList<>(List.of("to", "be", "or", "not", "to", "be"));
System.out.println("indexOf(be) " + words.indexOf("be") + ", lastIndexOf(be) " + words.lastIndexOf("be")
+ ", indexOf(xyz) " + words.indexOf("xyz"));
words.addAll(2, List.of("[", "]"));
words.addFirst("<");
words.addLast(">");
System.out.println(words + " first " + words.getFirst() + " last " + words.getLast());
// 7. ArrayList: a resizable array with fast get/set
var al = new ArrayList<Integer>(100); // initial capacity, size is 0
for (int i = 0; i < 5; i++) al.add(i * i);
al.set(2, -1);
System.out.println("ArrayList " + al + ", get(3) " + al.get(3) + ", size " + al.size());
al.trimToSize(); // release unused capacity
}
}
visited Ava, Ben -> [Ava, Cleo]
after add: [Ava, Jade, Kai, Ben, Cleo], nextIndex 3, previousIndex 2
xABC AxBC ABxC ABCx
backwards: dcba
after set and remove: [A, b, d]
iter2.next(): ConcurrentModificationException
remove p inside for each: ConcurrentModificationException
remove q inside for each: no exception, [p, r] (r was never visited)
removeIf: [r]
two iterators calling set: [PP, q, r]
merged: [Ann, Ben, Cid, Dot, Eve, Fay, Gus]
every second removed from b: [Ben, Fay]
a without b's elements: [Ann, Cid, Dot, Eve, Gus]
indexOf(be) 1, lastIndexOf(be) 5, indexOf(xyz) -1
[<, to, be, [, ], or, not, to, be, >] first < last >
ArrayList [0, 1, -1, 9, 16], get(3) 9, size 5
Trace the merge by hand once. aIter advances one element, then add drops the next element of b in behind it. When a runs out, hasNext() is false, so the remaining elements of b are appended at the end.
ArrayList: a resizable array
ArrayList wraps an ordinary array that it reallocates as needed. get(i) and set(i, e) are O(1), and iterating is very fast because the elements' references sit next to each other in memory.
Some internals worth knowing (OpenJDK):
- A
new ArrayList<>()starts with an empty shared array and allocates room for 10 elements on the firstadd. - When the array is full, it grows by about 50% (
newCapacity = old + old / 2). Appending is therefore amortized O(1). new ArrayList<>(n)andensureCapacity(n)pre-size the array when you know roughly how many elements are coming.trimToSize()gives unused capacity back.add(i, e)andremove(i)in the middle useSystem.arraycopy, which is a fast block move but still O(n).
LinkedList vs ArrayList: which one?
| Operation | ArrayList | LinkedList |
|---|---|---|
get(i), set(i, e) | O(1) | O(n) |
add(e) at the end | amortized O(1) | O(1) |
add(0, e), remove(0) | O(n) | O(1) |
| insert/remove in the middle through an iterator | O(n) shift | O(1) |
| find the middle position first | O(1) | O(n) walk |
| memory per element | one reference (plus spare capacity) | node object with three references (roughly 24–40 bytes extra) |
| CPU cache friendliness | excellent (contiguous) | poor (nodes scattered on the heap) |
The textbook rule says to use a linked list when you insert or remove in the middle a lot. Modern hardware shifts that balance hard toward ArrayList. System.arraycopy moves a contiguous block very quickly, while following scattered node pointers causes cache misses at every step. Benchmarks routinely show ArrayList winning even for many mid-list insertions, unless the lists are large and you are already positioned with an iterator.
Practical guidance:
- Default to
ArrayList. - For a queue, stack or double-ended queue, use
ArrayDeque. It is faster thanLinkedListforaddFirst,pollLastand the rest. - Reach for
LinkedListonly when a profiler shows that iterator-based insertion or removal in large lists is your bottleneck, or when you need aListand aDequein one object.
LinkedList implements both List and Deque, and since Java 21 both of those are SequencedCollections. That is why it has addFirst, addLast, getFirst, getLast, removeFirst, removeLast and reversed(). Since Java 21, ArrayList has these methods too, through List.
Common questions
Is LinkedList ever the right choice?
Rarely. It helps when you insert or remove many elements in a large list while you're already walking it with a ListIterator. For queues and stacks, ArrayDeque is faster. For everything else, ArrayList usually wins because its elements sit next to each other in memory.
Why is for (int i = 0; i < list.size(); i++) list.get(i) slow on a LinkedList?
Each get(i) walks from the nearer end of the list to index i, so the loop takes quadratic time. A for-each loop or an iterator moves one node per step and takes linear time.
What is the difference between Iterator and ListIterator?
A ListIterator can also move backward (previous, hasPrevious), report indexes (nextIndex, previousIndex), insert elements (add) and replace the last visited element (set). Only lists provide one.
Can I rely on ConcurrentModificationException to catch bugs?
No. The check is best effort, and some cases slip through. For example, removing the second-to-last element in a for-each loop ends the loop silently. Treat the exception as a debugging aid, and fix the code so that it never modifies a collection while another iterator is active.
Should I pre-size an ArrayList?
Only if you know roughly how many elements will be added and the list is large. new ArrayList<>(n) avoids repeated reallocation. For small lists, the default growth strategy (about 50% each time) is fine.
API reference
java.util.List<E>
| Method | Description |
|---|---|
ListIterator<E> listIterator() | list iterator positioned before the first element |
ListIterator<E> listIterator(int index) | list iterator positioned before index; the first next() returns get(index) |
void add(int i, E element) | inserts at position i |
boolean addAll(int i, Collection<? extends E> c) | inserts all elements of c at position i |
E remove(int i) | removes and returns the element at i |
E get(int i) | the element at i |
E set(int i, E element) | replaces the element at i and returns the old one |
int indexOf(Object o) | first position of an element equal to o, or −1 |
int lastIndexOf(Object o) | last position of an element equal to o, or −1 |
java.util.ListIterator<E>
| Method | Description |
|---|---|
void add(E e) | inserts before the cursor |
void set(E e) | replaces the element last returned by next or previous; throws IllegalStateException if neither was called, or if add or remove came after it |
boolean hasPrevious() | true if there is an element to the left |
E previous() | returns the element to the left and moves the cursor left; throws NoSuchElementException at the start |
int nextIndex() | index of the element next would return |
int previousIndex() | index of the element previous would return |
java.util.LinkedList<E>
| Method | Description |
|---|---|
LinkedList() | empty list |
LinkedList(Collection<? extends E> c) | list holding the elements of c |
void addFirst(E e), void addLast(E e) | add at either end |
E getFirst(), E getLast() | element at either end; throws NoSuchElementException if empty |
E removeFirst(), E removeLast() | remove and return the element at either end |
java.util.ArrayList<E>
| Method | Description |
|---|---|
ArrayList(), ArrayList(int initialCapacity) | empty list, optionally pre-sized |
ArrayList(Collection<? extends E> c) | list holding the elements of c |
void ensureCapacity(int min) | grows the backing array to at least min |
void trimToSize() | shrinks the backing array to the current size |
Summary
LinkedListis a doubly linked list. Removing or inserting at an iterator's position is O(1), but reaching a position is O(n).- A
ListIterator's cursor sits between elements.addinserts before the cursor, whileremoveandsetact on the element jumped over by the lastnextorprevious. - Iterators are fail-fast. A structural change by anyone other than the iterating iterator causes
ConcurrentModificationException.setis not structural. - Never loop with
get(i)over aLinkedList. Iterate instead. ArrayListis a growable array with O(1) indexed access and amortized O(1) appends. It is the right default list.ArrayDequeis the right default queue or stack.Vectoris a legacy class.
Practice Questions
A list holds A B C. You call listIterator(), then next(), next(), previous(), remove(). What does the list contain?
A C. After two next() calls the cursor is between B and C. previous() jumps back over B and returns it, so remove() deletes B, the element to the right of the cursor.
Why does ListIterator.add return void while Collection.add returns boolean?
Collection.add returns false when a collection like a set refuses a duplicate. Adding to a list through an iterator always changes the list, so there is nothing to report.
Two iterators traverse the same LinkedList and both call set. Is there a ConcurrentModificationException?
No. set replaces an element without changing the list's structure, so it doesn't touch the modification count that iterators check.
What is wrong with for (int i = 0; i \< list.size(); i++) sum += list.get(i); when list is a LinkedList?
Each get(i) walks the node chain from the nearer end, which is O(n). The loop as a whole is O(n²). A for-each loop over the same list is O(n).
Removing an element inside a for-each loop sometimes throws no exception. Why, and what goes wrong?
If you remove the second-to-last element, the hidden iterator's hasNext() compares its cursor with the now-smaller size and returns false. The loop ends without calling next(), so no check happens. The last element is never visited. Use removeIf or Iterator.remove instead.
You need a FIFO queue of tasks. Should you use LinkedList?
Prefer ArrayDeque. It implements Deque with a circular array, so it is faster and uses less memory than a chain of nodes. Use LinkedList only if you also need List operations or null elements, which ArrayDeque rejects.
Previous: Java Collection Interfaces: List, Set, Queue, Map and Sequenced Collections
Next: Java HashSet and TreeSet: Hash Tables, Hash Codes and Sorted Sets
Related reading
- Java Collection Interfaces: List, Set, Queue, Map and Sequenced Collections
- The Java Collections Framework: Interfaces, Implementations and Iterators
- Java ArrayList: Generic Array Lists Explained
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.