Java Set, Queue and Deque: HashSet, TreeSet, ArrayDeque and Their Methods (OCP 21)
Sets, queues and deques for the OCP 21 exam: HashSet, LinkedHashSet and TreeSet ordering, Set.of and Set.copyOf, null and Comparable rules, Queue methods that throw versus return null, Deque methods at both ends, stacks with push, pop and peek, and ArrayDeque versus LinkedList.
kvi5hnuCode Sprout team member6 min readOn this page
Lists let you hold anything in any order. Sets and queues add rules. A set refuses duplicates, and a queue releases elements in a fixed processing order. This article covers both, plus the double-ended deque, which can also act as a stack.
Sets
A Set contains no two elements that are equals to each other. add returns false, without an exception, when the element is already present. The three implementations differ in how they order the elements:
| Class | Storage | Iteration order | null | Elements must |
|---|---|---|---|---|
HashSet | hash table | unspecified | one null allowed | have sensible equals/hashCode |
LinkedHashSet | hash table + linked list | insertion order | one null allowed | have sensible equals/hashCode |
TreeSet | sorted tree | sorted (natural order or a Comparator) | not allowed (NullPointerException) | be Comparable, unless a Comparator is given |
for (Set<Integer> s : List.<Set<Integer>>of(new HashSet<>(), new LinkedHashSet<>(), new TreeSet<>())) {
s.add(66); s.add(10); s.add(66); s.add(8);
System.out.println(s);
}
// HashSet: e.g. [66, 8, 10] (any order)
// LinkedHashSet: [66, 10, 8]
// TreeSet: [8, 10, 66]
How a HashSet works matters for correctness. It uses hashCode() to pick a bucket, then equals() to compare within it. If you override equals without hashCode, "equal" objects can land in different buckets and both get stored.
A TreeSet compares elements to sort them. Adding an object that isn't Comparable (and no Comparator was given) compiles, but throws ClassCastException at run time. Adding null throws NullPointerException. TreeSet also implements NavigableSet, which adds methods such as first(), last(), lower(e), floor(e), ceiling(e), higher(e), headSet, tailSet and descendingSet().
TreeSet<Integer> seats = new TreeSet<>(List.of(4, 12, 7, 20));
seats.ceiling(8); // 12: smallest element >= 8
seats.lower(4); // null: nothing smaller than 4
Factory methods
Set<Character> letters = Set.of('c', 'a', 't'); // unmodifiable, unspecified order
Set<Character> copy = Set.copyOf(letters); // unmodifiable copy
Like List.of, these reject null and every modification. There's one difference to remember: Set.of('a', 'a') throws IllegalArgumentException for the duplicate, while Set.copyOf(List.of(1, 1, 2)) simply drops duplicates and returns a set of two elements.
Queues
A Queue holds elements waiting to be processed. Usually it's FIFO (first in, first out), like a line at a counter: you join at the back and leave from the front. Every operation exists in two versions:
| Operation | Throws an exception on failure | Returns a special value |
|---|---|---|
| add to the back | add(e) | offer(e) returns false |
| read the front | element() | peek() returns null |
| remove from the front | remove() | poll() returns null |
On an empty queue, element() and remove() throw NoSuchElementException, while peek() and poll() return null. Adding fails only for capacity-limited queues, which don't come up on the exam, so add and offer both return true in practice.
Queue<String> tickets = new ArrayDeque<>();
tickets.offer("T1");
tickets.add("T2");
tickets.peek(); // "T1", stays in the queue
tickets.poll(); // "T1", removed
tickets.poll(); // "T2"
tickets.poll(); // null: empty
tickets.remove(); // NoSuchElementException
Note that remove() without arguments removes the head. The inherited Collection method remove(Object) removes a specific element anywhere.
PriorityQueue (not required in depth) is a queue that hands out elements in sorted order instead of FIFO order.
Deques
A Deque ("deck", for double-ended queue) extends Queue and works at both ends. Its methods name the end explicitly:
| Operation | Front: throws | Front: special value | Back: throws | Back: special value |
|---|---|---|---|---|
| insert | addFirst(e) | offerFirst(e) | addLast(e) | offerLast(e) |
| read | getFirst() | peekFirst() | getLast() | peekLast() |
| remove | removeFirst() | pollFirst() | removeLast() | pollLast() |

The Queue methods keep their FIFO meaning on a deque. add and offer work at the back, while remove, poll, element and peek work at the front.
Using a deque as a stack
A stack is LIFO (last in, first out), like a pile of plates. Deque provides stack methods that all work at the front:
| Method | Same as | Empty deque |
|---|---|---|
push(e) | addFirst(e) | — |
pop() | removeFirst() | throws NoSuchElementException |
peek() | peekFirst() | returns null |
Deque<String> undo = new ArrayDeque<>();
undo.push("type A");
undo.push("type B");
undo.push("delete");
System.out.println(undo); // [delete, type B, type A]: front first
undo.pop(); // "delete"
undo.peek(); // "type B"
When you read deque code on the exam, first decide whether it's being used as a queue, a stack or a true double-ended queue. Mixing styles is legal and a classic trick: after push(1); offer(2); push(3); the deque is [3, 1, 2]. The Queue interface itself has no push or pop, so calling push on a variable declared as Queue doesn't compile.
ArrayDeque versus LinkedList
Both implement Deque:
ArrayDequeis the efficient choice for a pure queue or stack. It rejectsnullelements with aNullPointerException.LinkedListis also aList, and it acceptsnull. That makespeek()andpoll()ambiguous, becausenullcould mean "empty" or "the element is null".
The old Stack class still exists, but ArrayDeque is the recommended replacement.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
ArrayDequeis the current choice for both stacks and queues. The legacyStackclass still exists but isn't recommended.LinkedHashSet,SortedSetandDequeall became sequenced collections in Java 21 (article 57).
Exam traps from this article
A complete example
Arrivals go into a LinkedHashSet and a TreeSet to show the two orderings and the rejected duplicates. A TreeSet answers navigation questions, an ArrayDeque serves tickets FIFO, another acts as an undo stack, and a third is used at both ends.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.TreeSet;
public class Solution {
public static void main(String[] args) {
List<String> arrivals = List.of("Noor", "Eli", "Noor", "Ada", "Eli", "Cy");
// Sets: duplicates rejected; order depends on the class
Set<String> firstSeen = new LinkedHashSet<>(); // insertion order
Set<String> alphabetical = new TreeSet<>(); // sorted order
for (String name : arrivals) {
boolean isNew = firstSeen.add(name);
alphabetical.add(name);
if (!isNew) System.out.println("duplicate ignored: " + name);
}
System.out.println("LinkedHashSet " + firstSeen + ", TreeSet " + alphabetical);
TreeSet<Integer> seats = new TreeSet<>(List.of(4, 12, 7, 20));
System.out.println("seats " + seats + ": first=" + seats.first() + " ceiling(8)=" + seats.ceiling(8)
+ " lower(4)=" + seats.lower(4));
// Queue (FIFO): add/offer at the back, peek/poll at the front
Queue<String> tickets = new ArrayDeque<>();
tickets.offer("T1");
tickets.offer("T2");
tickets.add("T3");
System.out.println("queue " + tickets + " peek=" + tickets.peek());
while (!tickets.isEmpty()) System.out.print("serve " + tickets.poll() + "; ");
System.out.println("then poll=" + tickets.poll() + " peek=" + tickets.peek());
try {
tickets.remove(); // exception version
} catch (RuntimeException e) {
System.out.println("remove() on empty queue: " + e.getClass().getSimpleName());
}
// Deque as a stack (LIFO): push/pop/peek all work at the front
Deque<String> undo = new ArrayDeque<>();
undo.push("type A");
undo.push("type B");
undo.push("delete");
System.out.println("stack " + undo + " peek=" + undo.peek());
System.out.println("undo " + undo.pop() + ", undo " + undo.pop() + ", left " + undo);
// Deque at both ends
Deque<Integer> line = new ArrayDeque<>();
line.offerLast(5);
line.offerFirst(1);
line.addLast(9);
System.out.println("deque " + line + " first=" + line.peekFirst() + " last=" + line.peekLast()
+ " pollLast=" + line.pollLast() + " now " + line);
}
}
Output:
duplicate ignored: Noor
duplicate ignored: Eli
LinkedHashSet [Noor, Eli, Ada, Cy], TreeSet [Ada, Cy, Eli, Noor]
seats [4, 7, 12, 20]: first=4 ceiling(8)=12 lower(4)=null
queue [T1, T2, T3] peek=T1
serve T1; serve T2; serve T3; then poll=null peek=null
remove() on empty queue: NoSuchElementException
stack [delete, type B, type A] peek=delete
undo delete, undo type B, left [type A]
deque [1, 5, 9] first=1 last=9 pollLast=9 now [1, 5]
Points to notice:
addreturnsfalsefor the secondNoorandEli, and the program reports them.ceiling(8)finds the smallest seat number at least 8, andlower(4)returnsnullbecause nothing is smaller.- After the queue is drained,
pollandpeekreturnnull, butremove()throwsNoSuchElementException. - The stack prints front first,
[delete, type B, type A], sopopreturns the most recent action. offerFirstandofferLastbuild[1, 5, 9]from the middle outward.
Common questions
Why doesn't my HashSet of custom objects remove duplicates?
The class probably overrides equals but not hashCode, or neither. Both must be overridden consistently (records do it automatically).
Is Queue always FIFO?
No. FIFO is the usual behavior, but PriorityQueue orders by priority, and a deque used through push and pop is LIFO. The interface only says that there's a head that is processed next.
Which class should I use for a stack?
ArrayDeque, through the Deque interface with push, pop and peek.
Summary
- Sets reject duplicates using
equals(andhashCodefor hash-based sets).HashSethas no defined order,LinkedHashSetkeeps insertion order, andTreeSetsorts and offers navigation methods. Set.ofandSet.copyOfcreate unmodifiable, null-free sets.Set.ofrejects duplicates,Set.copyOfremoves them.Queuemethods come in pairs:add/offer,element/peek,remove/poll. The throwing ones fail withNoSuchElementExceptionon an empty queue.DequeaddsFirst/Lastversions for both ends, pluspush,popandpeekfor LIFO stack use at the front.ArrayDequeis the preferred queue or stack and rejectsnull.LinkedListis aListand aDeque, and allowsnull.
Practice quiz
Test yourself with the sets, queues and deques quiz: 10 exam-style questions with explanations.
Previous: Java List Interface: ArrayList, LinkedList, Factory Methods and List Operations (OCP 21)
Next: Java Map Interface: HashMap, TreeMap and Methods like merge and compute (OCP 21)
Related reading
- Java List Interface: ArrayList, LinkedList, Factory Methods and List Operations (OCP 21)
- Java Collections Framework: The Collection Interface and Common Methods (OCP 21)
- Java Variable Scope and Garbage Collection (OCP 21)
- Java Legacy Collections: Hashtable, Enumeration, Properties, Stack and BitSet
- Java Collections Algorithms: Sorting, Shuffling, Binary Search and Bulk Operations

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.