ArrayList vs LinkedList
ArrayList vs LinkedList is a favourite question because the textbook answer ("LinkedList is faster for inserts") is mostly wrong in practice. ArrayList wins almost every real workload because of memory locality.
What you will learn
- Explain how each is stored
- Compare complexity and real performance
- Know how ArrayList grows
Key concepts
ArrayList
Backed by an array. O(1) index access. When full, it grows by about 50% and copies elements, so add is amortized O(1). Inserting in the middle shifts elements, O(n).
LinkedList
A doubly linked list of nodes. O(1) add or remove at the ends or at an iterator position, but O(n) to find a position, and every node is a separate object with two pointers.
Cache locality
CPUs read memory in cache lines. Array elements sit next to each other, so iteration is very fast; linked nodes are scattered across the heap and cause cache misses.
Step by step
What to use
- Default: ArrayList
- Queue or stack: ArrayDeque
- Insert in the middle while iterating huge lists: LinkedList with a ListIterator, but measure first
- Known size: new ArrayList<>(n) to avoid resizes
Examples
Removing while iterating
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
// ConcurrentModificationException
// for (Integer n : nums) if (n % 2 == 0) nums.remove(n);
nums.removeIf(n -> n % 2 == 0); // correct and O(n)
// remove(int index) vs remove(Object)
nums.remove(1); // removes the element at index 1
nums.remove(Integer.valueOf(1)); // removes the value 1Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Benchmark summing 1 million ints in ArrayList vs LinkedList with JMH.
- Explain why LinkedList.get(i) in a loop is O(n²).
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
When is LinkedList actually better?
Rarely: when you hold an iterator in the middle of a large list and do many inserts or removes at that point. For queues ArrayDeque is better, and for most other cases ArrayList is.
What is the default capacity of ArrayList?
A new ArrayList() starts with an empty shared array and allocates 10 on the first add; after that it grows to about 1.5× the old capacity when full.
Summary
ArrayList is a resizable array with fast index access and great locality; LinkedList has cheap end operations but slow access and high memory use. Default to ArrayList and ArrayDeque.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus