Sub topic 7
LinkedList vs ArrayList
You already know ArrayList. Java has a second list type called LinkedList. Both follow the List interface. An interface is a set of methods a class promises to have. So both types have add, get, set, remove, and size. They store their elements in different ways, and that changes how fast each one is at certain jobs.
How each one stores data
An ArrayList keeps its elements in an array. An array is a row of numbered slots placed side by side in memory. To read slot 500, Java jumps straight to it. That makes get(index) very fast.
A LinkedList keeps each element in a node. A node is a small object that holds one element plus links to the node before it and the node after it. To reach element 500, Java starts at one end and follows 500 links. That makes get(index) slow on a big list.
Where each one is faster
Adding or removing at the front works the other way around. An ArrayList has to shift every other element over by one slot. A LinkedList only changes a couple of links.
| Task | ArrayList | LinkedList |
|---|---|---|
| Read by index, `get(i)` | Fast | Slow, has to walk the links |
| Add at the end | Fast | Fast |
| Add or remove at the front | Slow, shifts every element | Fast |
| Memory per element | Small | Larger, each node stores two links |
Using LinkedList in code
Since both types are Lists, you can swap one for the other. LinkedList also has extra methods for working at the two ends: addFirst, addLast, getFirst, and removeFirst.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class LinkedListDemo {
public static void main(String[] args) {
List<String> array = new ArrayList<>(List.of("Ana", "Ben", "Cara"));
List<String> linked = new LinkedList<>(array);
System.out.println(array.get(1)); // Ben
System.out.println(linked.get(1)); // Ben, same result, slower on big lists
LinkedList<String> line = new LinkedList<>();
line.addLast("first");
line.addLast("second");
line.addFirst("urgent");
System.out.println(line); // [urgent, first, second]
System.out.println(line.getFirst()); // urgent
System.out.println(line.removeFirst()); // urgent
System.out.println(line); // [first, second]
}
}The variable linked has the type List<String>. Writing it that way lets you switch to ArrayList later by changing one word.
Exercises
Exercise
Your program reads a list of 100,000 scores and often looks up a score by its position, for example scores.get(42000). Should you use ArrayList or LinkedList?
Show answer
ArrayList. It jumps straight to any index. A LinkedList would have to follow tens of thousands of links to reach position 42000.
Exercise
What does this code print? LinkedList<Integer> q = new LinkedList<>(); q.addLast(1); q.addLast(2); q.addFirst(0); q.removeFirst(); System.out.println(q);
Show answer
It prints [1, 2]. After the three adds the list is [0, 1, 2], and removeFirst takes away the 0.