Sub topic 7
LinkedList vs ArrayList
You already know ArrayList, which is a list that keeps items in order and lets you reach any item by its index. Java has a second common list called LinkedList. Both classes implement the List interface, so they share methods like add, get, set, remove, and size. The difference is how each one stores its items inside. That inner layout makes some jobs fast in one list and slow in the other.
This chapter shows how each list works, what each one is good at, and why ArrayList is the usual default.
Two ways to store a sequence
How ArrayList stores items
An ArrayList keeps its items in a plain Java array behind the scenes. This is called the backing array. All the slots sit next to each other in memory, numbered from 0.
- To read item 5, Java jumps straight to slot 5. That takes the same time whether the list holds 10 items or 10 million.
- To add an item at the end, Java writes it into the next free slot.
- When the array is full,
ArrayListmakes a bigger array (about 1.5 times the old size) and copies every item over. This copying is rare, so adding at the end is still fast on average. - To insert or remove an item at the front, every later item must move over by one slot. This is called shifting. With a million items, that means a million moves.
How LinkedList stores items
A LinkedList keeps each item in its own small object called a node. A node holds three things:
- The item itself.
- A link to the next node.
- A link to the previous node.
Since every node links both ways, this is a doubly linked list. The list itself only remembers the first node (the head) and the last node (the tail).
- To add or remove at the front or the back, Java changes a few links. No items move.
- To read item 5, Java has no shortcut. It starts at the head and follows links one by one until it reaches node 5. (It starts from the tail if that end is closer.) With a big list, this walk is slow.
Talking about speed
Programmers describe speed by how the work grows as the list gets bigger.
- Constant time means the work stays the same no matter the size. It is written O(1).
- Linear time means the work grows with the size. Twice the items means about twice the work. It is written O(n), where n is the number of items.
You do not need the math. Just read O(1) as "fast at any size" and O(n) as "slower as the list grows."
| Operation | ArrayList | LinkedList |
|---|---|---|
| `get(i)` / `set(i, x)` | O(1), jumps to the slot | O(n), walks the links |
| `add(x)` at the end | O(1) on average | O(1) |
| `add(0, x)` at the front | O(n), shifts everything | O(1) |
| `remove(0)` from the front | O(n), shifts everything | O(1) |
| Insert in the middle by index | O(n), shifts half on average | O(n), walks to the spot first |
| Memory per item | Small: one slot | Larger: a node with two extra links |
The middle row surprises many beginners. People often say "LinkedList is fast at inserting," but that is only true once you are already at the right node. Finding the node by index still means walking there.
Using LinkedList
LinkedList has every List method. It also has extra methods for working at the two ends: addFirst, addLast, getFirst, getLast, removeFirst, and removeLast. These come from the Deque interface. A deque, said "deck," is a double-ended queue, meaning a line you can add to or take from at either end.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<String> line = new LinkedList<>();
line.add("Ana");
line.add("Ben");
line.addFirst("Zoe");
System.out.println(line); // [Zoe, Ana, Ben]
System.out.println(line.getFirst()); // Zoe
System.out.println(line.getLast()); // Ben
line.removeFirst();
System.out.println(line); // [Ana, Ben]
System.out.println(line.get(1)); // Ben (works, but walks the links)
List<String> copy = new ArrayList<>(line);
copy.add(0, "Max");
System.out.println(copy); // [Max, Ana, Ben]
}
}Because both classes implement List, you can declare a variable as List<String> and switch the class on the right side later. The rest of your code does not change.
List<String> names = new ArrayList<>();
// later, if you really need it:
// List<String> names = new LinkedList<>();Seeing the difference with a timing test
The program below runs two tests on each list. The first test adds items at the front, which favors LinkedList. The second test reads every item by index, which favors ArrayList.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class ListTiming {
static long addAtFront(List<Integer> list, int n) {
long start = System.nanoTime();
for (int i = 0; i < n; i++) {
list.add(0, i);
}
return (System.nanoTime() - start) / 1_000_000;
}
static long readByIndex(List<Integer> list) {
long start = System.nanoTime();
long sum = 0;
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
}
if (sum < 0) System.out.println("never printed");
return (System.nanoTime() - start) / 1_000_000;
}
public static void main(String[] args) {
int n = 50_000;
List<Integer> array = new ArrayList<>();
List<Integer> linked = new LinkedList<>();
System.out.println("Add at front, ArrayList: " + addAtFront(array, n) + " ms");
System.out.println("Add at front, LinkedList: " + addAtFront(linked, n) + " ms");
System.out.println("Read by index, ArrayList: " + readByIndex(array) + " ms");
System.out.println("Read by index, LinkedList: " + readByIndex(linked) + " ms");
}
}Your exact numbers will depend on your computer. You should still see that LinkedList wins the first test and loses the second one by a lot. The second loop is slow because every get(i) call starts a new walk through the nodes.
Hidden costs of LinkedList
The table does not show everything. LinkedList has two more costs.
- Memory. Each node is a separate object with two extra links plus object overhead. A
LinkedListoften uses several times more memory than anArrayListwith the same items. - Scattered data. Array slots sit side by side, so the processor can read them quickly in a row. Nodes can be spread all over memory, so even a simple for-each loop is usually slower on a
LinkedList.
Because of these costs, ArrayList often beats LinkedList even for jobs that sound like linked-list work.
Which one should you pick?
Start with ArrayList. It is the right choice for most programs.
Consider LinkedList only when all of these are true:
- You mostly add or remove at the ends, or in the middle while already walking the list with an Iterator.
- You rarely read items by index.
- You have measured your program and found that the list is the slow part.
| Your situation | Good choice |
|---|---|
| General-purpose list, frequent `get(i)` | `ArrayList` |
| Add to the end, then loop over everything | `ArrayList` |
| Queue or stack working at the ends | `ArrayDeque` (or `LinkedList`) |
| Many removals while walking with an Iterator | `LinkedList` can help, but measure first |
Exercise
You have a List<String> with 100,000 names. Your program calls get(i) with random indexes thousands of times. Should the list be an ArrayList or a LinkedList, and why?
Show answer
Use an ArrayList. get(i) on an ArrayList jumps straight to the slot in constant time, O(1). On a LinkedList, each get(i) walks node by node from the nearer end, O(n), which is slow with 100,000 items.
Exercise
A friend says, "LinkedList is always faster for inserting in the middle." What is wrong with this claim when you insert with list.add(50_000, x)?
Show answer
The LinkedList first has to walk about 50,000 links to find position 50,000, which takes O(n) time. Only the final relinking is O(1). An ArrayList also takes O(n) because it shifts the later items, and in practice the ArrayList is often faster because moving items in an array is quick.
Exercise
Which LinkedList methods let you add, read, and remove at the front of the list, and which other class is usually a better choice for that job?
Show answer
addFirst, getFirst, and removeFirst work on the front (addLast, getLast, and removeLast work on the back). ArrayDeque offers the same methods and is usually faster and uses less memory.