Java LinkedList in Depth
A LinkedList links each item to the next one in line. Used as a queue, it adds at the tail and takes from the head.
A queue in action
offer places three names at the tail, in order. poll then takes them from the head, first in and first out.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> line = new LinkedList<>();
line.offer("Ana");
line.offer("Ben");
line.offer("Cid");
while (!line.isEmpty()) {
System.out.println(line.poll());
}
}
}Peek leaves the head in place
peek reads the head without taking it. The size printed after it is still three.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> line = new LinkedList<>();
line.offer("Ana");
line.offer("Ben");
line.offer("Cid");
System.out.println(line.peek());
System.out.println(line.size());
}
}Working at both ends
addFirst puts an item before the current head. addLast puts an item after the current tail.
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> names = new LinkedList<>();
names.add("Ben");
names.addFirst("Ana");
names.addLast("Cid");
System.out.println(names);
}
}Example
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> line = new LinkedList<>();
line.offer("Ana");
line.offer("Ben");
line.offer("Cid");
line.offer("Dan");
System.out.println(line.poll());
System.out.println(line.poll());
System.out.println(line.peek());
System.out.println(line.size());
}
}Key points
- The Queue interface is a contract for first-in, first-out lines, and LinkedList follows it.
- offer adds an item at the tail of the queue.
- poll removes and returns the head item, or null when the queue is empty.
- peek returns the head item without removing it.
- addFirst and addLast place an item directly at either end of the list.
In this example, poll serves the first two people in line, peek shows Cid at the head, and two people remain in the queue.
Note
Reading an item by index walks the links, so ArrayList is the better default for index-heavy work.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does poll return when a queue is empty?