Queue & Comparators
PriorityQueues, Deques, Comparable vs Comparator interfaces
- Understand Queues and Deques
- Implement custom sorting with Comparable
- Write flexible sorting logic using Comparator and Lambdas
Table of Contents
- Queue Interface
- Queue Methods — Detailed Reference
- PriorityQueue
- Min PriorityQueue (Default)
- Max PriorityQueue (with Comparator)
- PriorityQueue Time Complexities
- The Sorting Problem — Why Comparator & Comparable Exist
- Comparator Interface
- Sorting Primitives vs Objects
- Comparable Interface
- Comparator vs Comparable — Full Comparison
- Practice Questions
- Interview Notes
- Summary Revision Bullets
1. Queue Interface
Overview
A Queue is a linear data structure that models the concept of a real-world queue (line of people). In Java, Queue is an interface in the java.util package and is a child (sub-interface) of the Collection interface.
Why This Concept Exists
In many programming problems you need to process elements in the order they arrive — first come, first served. The Queue interface formalizes this ordering and provides a standard API for it.
Definition
A Queue is a collection designed for holding elements prior to processing. It follows — by default — the FIFO (First In, First Out) principle: the element added first is the one removed first.
Real-world Analogy
Imagine a movie-theater ticket counter:
- People join the line at the rear (back).
- People get their ticket and leave from the front.
- Whoever arrived first gets served first — First In, First Out.
FIFO Principle Illustrated
1Rear → [New items added here]2Front ← [Items removed here]3
4Queue state after adding 10, 20, 30:5Front → [ 10 | 20 | 30 ] ← Rear6
7After one remove (poll):8Front → [ 20 | 30 ] ← Rear (10 was returned and removed)Queue in the Java Collection Hierarchy
Queue is a sub-interface of Collection, which is itself a sub-interface of Iterable. Therefore, every Queue implementation inherits all methods from both Collection and Iterable, plus the Queue-specific methods.Key Observations
- Queue generally follows FIFO, but not always —
PriorityQueueis a notable exception. - Queue is an interface, not a class — you cannot instantiate it directly.
- Concrete implementations:
PriorityQueue,LinkedList,ArrayDeque.
2. Queue Methods Detailed Reference
Queue adds six new methods on top of everything inherited from Collection. These six methods come in three pairs, where each pair does the same operation but differs in how it handles failure (exception vs. special return value).
The Six Methods at a Glance
| Operation | Throws Exception on Failure | Returns Special Value on Failure |
|---|---|---|
| Insert | add(e) | offer(e) |
| Remove & Return Head | remove() | poll() |
| Inspect Head (no remove) | element() | peek() |
Method 1: `add(e)`
Purpose: Insert an element into the queue.
Behavior:
- Returns
trueif insertion is successful. - Throws an exception if insertion fails (e.g., capacity-restricted queue is full).
- Throws
NullPointerExceptionif you try to insertnull.
1Queue<Integer> queue = new LinkedList<>();2queue.add(5); // Inserts 5 — returns true3queue.add(null); // Throws NullPointerExceptionMethod 2: `offer(e)`
Purpose: Insert an element into the queue.
Behavior:
- Exactly the same as
add(e)in most cases. - The only difference: if insertion fails,
offerreturnsfalseinstead of throwing an exception. - This is preferred for capacity-constrained queues.
1Queue<Integer> queue = new LinkedList<>();2boolean result = queue.offer(10); // returns true| Aspect | add(e) | offer(e) |
|---|---|---|
| On success | Returns true | Returns true |
| On failure | Throws exception | Returns false |
| Null allowed? | No (NPE) | No (NPE) |
Method 3: `poll()`
Purpose: Retrieve and remove the head (front) of the queue.
Behavior:
- Returns the element at the head.
- Also removes that element from the queue.
- Returns
nullif the queue is empty (does NOT throw an exception).
1Queue<Integer> queue = new LinkedList<>();2queue.add(1);3queue.add(2);4Integer head = queue.poll(); // Returns 1, queue now contains [2]5queue.poll(); // Returns 2, queue is now empty6queue.poll(); // Returns null (queue empty, no exception)Method 4: `remove()`
Purpose: Retrieve and remove the head of the queue.
Behavior:
- Same as
poll(), but if the queue is empty, it throwsNoSuchElementExceptioninstead of returningnull.
1Queue<Integer> queue = new LinkedList<>();2queue.add(42);3queue.remove(); // Returns 424queue.remove(); // Throws NoSuchElementException — queue is empty| Aspect | poll() | remove() |
|---|---|---|
| Removes head? | Yes | Yes |
| Returns head value? | Yes | Yes |
| If queue empty | Returns null | Throws NoSuchElementException |
Method 5: `peek()`
Purpose: Retrieve (look at) the head of the queue without removing it.
Behavior:
- Returns the element at the front.
- Does not modify the queue.
- Returns
nullif the queue is empty.
1Queue<Integer> queue = new LinkedList<>();2queue.add(7);3queue.add(8);4Integer head = queue.peek(); // Returns 7, queue still contains [7, 8]Method 6: `element()`
Purpose: Retrieve (look at) the head of the queue without removing it.
Behavior:
- Same as
peek(), but if the queue is empty, throwsNoSuchElementException.
1Queue<Integer> queue = new LinkedList<>();2queue.element(); // Throws NoSuchElementException — empty queue| Aspect | peek() | element() |
|---|---|---|
| Removes head? | No | No |
| Returns head value? | Yes | Yes |
| If queue empty | Returns null | Throws NoSuchElementException |
Complete Method Summary Table
| Method | Action | Failure Behavior |
|---|---|---|
add(e) | Insert at rear | Exception |
offer(e) | Insert at rear | Return false |
remove() | Remove & return head | Exception |
poll() | Remove & return head | Return null |
element() | Inspect head | Exception |
peek() | Inspect head | Return null |
add, remove, element) are the "strict" ones. The methods that return special values (offer, poll, peek) are the "safe" ones.3. PriorityQueue
Overview
PriorityQueue is the most commonly used concrete implementation of the Queue interface in Java. Unlike a standard FIFO queue, PriorityQueue does not follow FIFO order. Instead, elements are ordered based on their priority.
Why PriorityQueue Exists
In many real-world scenarios, you don't want to process things in arrival order — you want to process the most important (or least important) item first. Examples:
- Task scheduling (highest-priority task runs first).
- Dijkstra's shortest-path algorithm (always process the nearest node).
- Heap Sort.
- Finding the k-th largest/smallest element efficiently.
Definition
PriorityQueueis a class that implements theQueueinterface and internally uses a heap data structure to maintain element ordering. By default it is a min-heap (minimum element is always at the front/head).
PriorityQueue is Heap in Disguise
| PriorityQueue Type | Equivalent Heap |
|---|---|
| Default (no comparator) | Min-Heap |
| With reverse comparator | Max-Heap |
PriorityQueue. There is no separate Heap class in Java's standard library.Internal Structure Heap
A heap is a complete binary tree stored as an array where:
- Min-Heap: Every parent node ≤ its children. The smallest element is at the root.
- Max-Heap: Every parent node ≥ its children. The largest element is at the root.
When you add or remove an element, the heap performs a heapify operation to restore the heap property.
1Min-Heap example with elements 1, 2, 5, 8:2
3 1 ← root (minimum)4 / \5 2 56 /7 8How Elements Are Ordered
1Elements are ordered according to:21. Natural ordering (default) — ascending for numbers, lexicographic for strings32. A Comparator provided at construction time4. Min PriorityQueue (Default)
Creating a Default (Min) PriorityQueue
When you create a PriorityQueue with an empty constructor, it uses natural ordering, which for integers means ascending order — the smallest element is always at the head. This is equivalent to a min-heap.
1PriorityQueue<Integer> minPQ = new PriorityQueue<>();Step-by-Step Insertion Example
Let's insert: 5, 2, 8, 1
Step 1 — Insert 5:
1 5Step 2 — Insert 2: (2 < 5, so heapify upward — swap 2 and 5)
1 22 /3 5Step 3 — Insert 8: (8 > 2, no heapify needed)
1 22 / \3 5 8Step 4 — Insert 1: (1 < 5, swap; then 1 < 2, swap again)
1 12 / \3 2 84 /5 5Full Code Example Min PriorityQueue
1import java.util.PriorityQueue;2
3public class MinPriorityQueueExample {4
5 public static void main(String[] args) {6
7 // Step 1: Create a default (min) PriorityQueue8 PriorityQueue<Integer> minPQ = new PriorityQueue<>();9
10 // Step 2: Insert elements11 minPQ.add(5);12 minPQ.add(2);13 minPQ.add(8);14 minPQ.add(1);15
16 // Step 3: Print internal level-order representation17 System.out.println("Internal state: " + minPQ);18
19 // Step 4: Remove elements one by one using poll()20 System.out.println("Removing elements:");21 while (!minPQ.isEmpty()) {22 System.out.println(minPQ.poll());23 }24 }25}Output
1Internal state: [1, 2, 8, 5]2Removing elements:31425568Line-by-Line Explanation
| Line | Explanation |
|---|---|
new PriorityQueue<>() | Creates a min-heap. No comparator provided → natural (ascending) order. |
minPQ.add(5) | Inserts 5 as root. |
minPQ.add(2) | Inserts 2; heapify pushes 2 above 5. |
minPQ.add(8) | Inserts 8; 8 > 2, no swap needed. |
minPQ.add(1) | Inserts 1; heapify swaps 1 up to root. |
System.out.println(minPQ) | Prints the internal array representation (level-order). Not sorted output — it shows the heap array. |
minPQ.poll() | Removes and returns the minimum (root). After each poll, heapify re-establishes heap property. |
PriorityQueue with System.out.println() does not print elements in sorted order. It prints the internal heap array. To get sorted output, use poll() in a loop.Why Poll Gives Sorted Output
- Each
poll()removes the root (minimum) and then heapifies. - After removing 1: heap becomes
[2, 5, 8]; root is 2. - After removing 2: heap becomes
[5, 8]; root is 5. - After removing 5: heap becomes
[8]; root is 8. - Polling repeatedly always gives the next minimum → ascending order output.
5. Max PriorityQueue (with Comparator)
Creating a Max PriorityQueue
To create a max-heap (largest element at the head), you must provide a Comparator that reverses the natural ordering.
1PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a, b) -> b - a);This comparator tells the PriorityQueue: "Store elements in reverse (descending) order."
Full Code Example Max PriorityQueue
1import java.util.PriorityQueue;2
3public class MaxPriorityQueueExample {4
5 public static void main(String[] args) {6
7 // Create a max-heap using a reverse-order comparator8 PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a, b) -> b - a);9
10 // Insert elements11 maxPQ.add(5);12 maxPQ.add(2);13 maxPQ.add(8);14 maxPQ.add(1);15
16 // Internal state17 System.out.println("Internal state: " + maxPQ);18
19 // Remove elements one by one20 System.out.println("Removing elements:");21 while (!maxPQ.isEmpty()) {22 System.out.println(maxPQ.poll());23 }24 }25}Output
1Internal state: [8, 2, 5, 1]2Removing elements:38455261Step-by-Step Insertion into Max PQ
Inserting: 5, 2, 8, 1
After 5: [5]
After 2: 2 < 5, no swap (max-heap: parent must be ≥ child, 5 ≥ 2 ✓)
1 52 /3 2After 8: 8 > 5, swap (heapify up)
1 82 / \3 2 5After 1: 1 < 2, no swap needed
1 82 / \3 2 54 /5 1Polling gives: 8 → 5 → 2 → 1 (descending order).
Why `(a, b) -> b - a` Creates a Max-Heap
The comparator returns b - a. When b > a, this is positive → the sorting algorithm interprets this as "a should come after b" → larger elements bubble to the front. See the full explanation in Section 8.
6. PriorityQueue Time Complexities
| Operation | Time Complexity | Reason |
|---|---|---|
add(e) / offer(e) | O(log N) | Heapify-up after insertion |
peek() / element() | O(1) | Just read the root — no traversal |
poll() / remove() (head) | O(log N) | Remove root, heapify-down |
remove(Object o) (arbitrary) | O(N) | Must find element (linear scan) then heapify |
| Build heap from N elements | O(N log N) | N insertions, each O(log N) |
peek() is O(1) because the minimum (or maximum) is always at index 0 of the internal array — it's instantly accessible without any traversal.7. The Sorting Problem Why Comparator & Comparable Exist
The Core Problem
Sorting algorithms need to compare two elements to decide their order. The key question is: "Should these two elements be swapped?"
For primitive types (int, double, char), comparison is trivial — use <, >, ==.
But for custom objects (like a Car class), Java has no idea how to compare them. Should two Car objects be compared by name? By price? By year? Java cannot guess — you must tell it.
Problem 1 Sorting in a Different Order
Even for primitive wrappers like Integer, Arrays.sort() always sorts in ascending order by default. If you want descending order, you need a way to override the comparison logic.
Problem 2 Sorting Custom Objects Throws an Exception
1class Car {2 String carName;3 String carType;4
5 Car(String carName, String carType) {6 this.carName = carName;7 this.carType = carType;8 }9}10
11Car[] carArray = new Car[3];12carArray[0] = new Car("SUV", "Petrol");13carArray[1] = new Car("Sedan", "Diesel");14carArray[2] = new Car("Hatchback", "CNG");15
16Arrays.sort(carArray); // ❌ ClassCastException: Car cannot be cast to ComparableWhy This Exception Occurs
Internally, Arrays.sort() calls compareTo() on the objects being compared. Integer and String implement Comparable, so they have a compareTo() method. But our Car class does not implement Comparable and has no compareTo() method — so Java cannot compare two Car objects and throws ClassCastException.
The Solution
Java provides two mechanisms to define comparison logic for objects:
| Mechanism | How it works |
|---|---|
| Comparable | The object defines its own comparison logic (compareTo) |
| Comparator | An external class/lambda defines the comparison logic (compare) |
How the Sorting Algorithm Uses Comparison
All of Java's sorting algorithms (merge sort, tim sort, quicksort) follow this contract internally:
1if compare(objectOne, objectTwo) > 0 → swap them2if compare(objectOne, objectTwo) == 0 → do nothing (equal)3if compare(objectOne, objectTwo) < 0 → do nothing (already in correct order)So the comparison method only needs to return a positive, zero, or negative number. The sorting algorithm does the rest.
8. Comparator Interface
Overview
Comparator is a functional interface in java.util that defines a single abstract method compare(T o1, T o2). It allows you to define comparison logic externally — without modifying the class being compared.
Definition
1@FunctionalInterface2public interface Comparator<T> {3 int compare(T o1, T o2);4}The `compare` Contract
1compare(o1, o2) > 0 → o1 is "greater than" o2 (swap: put o2 before o1)2compare(o1, o2) == 0 → o1 equals o2 (no swap)3compare(o1, o2) < 0 → o1 is "less than" o2 (no swap: o1 stays before o2)How the Sorting Algorithm Uses `compare`
Example 1 Sorting Integer Array in Ascending Order
1import java.util.Arrays;2
3public class ComparatorAscending {4 public static void main(String[] args) {5 Integer[] arr = {17, 3, 5, 1, 10};6
7 Arrays.sort(arr, (val1, val2) -> val1 - val2);8
9 System.out.println(Arrays.toString(arr));10 }11}Output
1[1, 3, 5, 10, 17]Why `val1 - val2` Produces Ascending Order
Let's trace: comparing 6 and 11.
val1 = 6,val2 = 11val1 - val2 = 6 - 11 = -5→ negative → do not swap- So 6 stays before 11 → small numbers stay at front → ascending order ✓
Let's trace: comparing 9 and 1.
val1 = 9,val2 = 1val1 - val2 = 9 - 1 = 8→ positive → swap- 1 moves before 9 → small numbers move to front → ascending order ✓
Example 2 Sorting Integer Array in Descending Order
1import java.util.Arrays;2
3public class ComparatorDescending {4 public static void main(String[] args) {5 Integer[] arr = {6, 4, 1, 9, 2, 11};6
7 Arrays.sort(arr, (val1, val2) -> val2 - val1); // <-- reversed8
9 System.out.println(Arrays.toString(arr));10 }11}Output
1[11, 9, 6, 4, 2, 1]Why `val2 - val1` Produces Descending Order
Let's trace: comparing 6 and 11.
val1 = 6,val2 = 11val2 - val1 = 11 - 6 = 5→ positive → swap (put 11 before 6)- Larger numbers move to front → descending order ✓
Let's trace: comparing 9 and 1.
val1 = 9,val2 = 1val2 - val1 = 1 - 9 = -8→ negative → do not swap (9 stays before 1)- Larger numbers stay at front → descending order ✓
compare returns. By swapping val1 - val2 to val2 - val1, we flip the sign of every comparison result, which flips the entire sort order.The Ascending vs Descending Formula
| Desired Order | Formula | Logic |
|---|---|---|
| Ascending | val1 - val2 | Positive when val1 > val2 → swap → smaller stays first |
| Descending | val2 - val1 | Positive when val2 > val1 → swap → larger stays first |
Example 3 Sorting Custom Object (Car) by Type, Descending
1import java.util.Arrays;2
3public class CarSortByTypeDesc {4 public static void main(String[] args) {5 Car[] carArray = {6 new Car("SUV", "Petrol"),7 new Car("Sedan", "Diesel"),8 new Car("Hatchback", "CNG")9 };10
11 Arrays.sort(carArray, (o1, o2) -> o2.carType.compareTo(o1.carType));12
13 for (Car c : carArray) {14 System.out.println(c.carName + " - " + c.carType);15 }16 }17}Output
1SUV - Petrol2Sedan - Diesel3Hatchback - CNG(Sorted by carType in descending/reverse-lexicographic order: Petrol → Diesel → CNG)
Explanation
o2.carType.compareTo(o1.carType)is the string equivalent ofval2 - val1.String.compareTo()returns positive if the calling string is lexicographically greater, negative if less, zero if equal.- By putting
o2first, we get descending lexicographic order oncarType.
Example 4 Sorting Custom Object (Car) by Name, Ascending
1Arrays.sort(carArray, (o1, o2) -> o1.carName.compareTo(o2.carName));o1.carName.compareTo(o2.carName)→ ascending lexicographic order oncarName.- Hatchback < Sedan < SUV (alphabetically) → output: Hatchback, Sedan, SUV.
Example 5 Sorting Custom Object (Car) by Name, Descending
1Arrays.sort(carArray, (o1, o2) -> o2.carName.compareTo(o1.carName));- Reversed: SUV > Sedan > Hatchback → output: SUV, Sedan, Hatchback.
Three Ways to Provide a Comparator
Since Comparator is a functional interface, there are three equivalent ways to implement it:
Way 1 Lambda Expression (Recommended)
1Arrays.sort(carArray, (o1, o2) -> o1.carName.compareTo(o2.carName));Way 2 Anonymous Inner Class
1Arrays.sort(carArray, new Comparator<Car>() {2 @Override3 public int compare(Car o1, Car o2) {4 return o1.carName.compareTo(o2.carName);5 }6});Way 3 Separate Named Class
1class CarNameComparator implements Comparator<Car> {2 @Override3 public int compare(Car o1, Car o2) {4 return o2.carName.compareTo(o1.carName); // descending5 }6}7
8// Usage:9Arrays.sort(carArray, new CarNameComparator());10
11// Or with a List:12List<Car> carList = new ArrayList<>();13carList.add(new Car("SUV", "Petrol"));14carList.add(new Car("Sedan", "CNG"));15Collections.sort(carList, new CarNameComparator());How `Collections.sort` and `Arrays.sort` Relate
Internally, Collections.sort(list) converts the list to an array and then calls Arrays.sort() on it. So understanding Arrays.sort with comparators gives you a complete understanding of both.
Using Comparator in PriorityQueue Constructor
1// Max-Heap: elements stored in descending order2PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a, b) -> b - a);3
4// The constructor accepts: PriorityQueue(Comparator<? super E> comparator)5// The comparator tells the PQ how to order elements.6// b - a → when b > a, result is positive → b comes before a → largest firstKey Observations on Comparator
Comparatoris external to the class being compared.- You can have multiple
Comparatorimplementations for the same class (by name, by type, ascending, descending, etc.). - You do not need to modify the class you are sorting.
- Since it's a functional interface, lambda expressions work perfectly.
- The sorting algorithm itself never changes — only the
compareimplementation changes.
9. Sorting Primitives vs Objects
Why `Arrays.sort(int[])` Works Without Comparator
1int[] arr = {1, 2, 3, 4};2Arrays.sort(arr); // Works fineFor primitive arrays, Java uses a direct quicksort implementation that uses < and > operators directly. No compare method is needed — comparing primitives is trivial.
Why `Arrays.sort(Object[])` Needs Comparable or Comparator
For object arrays (like Integer[], Car[], String[]), Java's sorting algorithm calls compareTo() on the objects (via the Comparable interface) or calls compare() on a provided Comparator.
Integer→ implementsComparable→ hascompareTo()→ works without a ComparatorString→ implementsComparable→ hascompareTo()→ works without a ComparatorCar(custom) → does NOT implementComparable→ has nocompareTo()→ must provide Comparator or implement Comparable
10. Comparable Interface
Overview
Comparable is an interface in java.lang that allows an object to define its own natural ordering. A class that implements Comparable can be sorted by Arrays.sort() or Collections.sort() without providing any external Comparator.
Definition
1public interface Comparable<T> {2 int compareTo(T o);3}Note: Comparable has only one parameter (T o) — the object being compared TO. The first object is this (the object calling the method).
The `compareTo` Contract
1this.compareTo(o) > 0 → this is "greater than" o (swap: put o before this)2this.compareTo(o) == 0 → this equals o3this.compareTo(o) < 0 → this is "less than" o (no swap: this stays before o)Integer's Built-in `compareTo`
Integer implements Comparable:
1// Inside the Integer class (simplified):2public int compareTo(Integer anotherInteger) {3 int x = this.value;4 int y = anotherInteger.value;5 return (x < y) ? -1 : ((x == y) ? 0 : 1);6}x < y→ return -1 (negative) → no swap → ascending order.x == y→ return 0 → equal.x > y→ return 1 (positive) → swap → ascending order.
This is why Arrays.sort(Integer[]) always gives ascending order when no comparator is provided — because Integer.compareTo() is hardcoded for ascending order.
How the Sorting Algorithm Uses `compareTo`
Example Making Car Implement Comparable
1import java.util.ArrayList;2import java.util.Collections;3import java.util.List;4
5class Car implements Comparable<Car> {6 String carName;7 String carType;8
9 Car(String carName, String carType) {10 this.carName = carName;11 this.carType = carType;12 }13
14 @Override15 public int compareTo(Car other) {16 // Sort by carType in ascending (lexicographic) order17 return this.carType.compareTo(other.carType);18 }19
20 @Override21 public String toString() {22 return carName + " (" + carType + ")";23 }24}25
26public class ComparableExample {27 public static void main(String[] args) {28 List<Car> carList = new ArrayList<>();29 carList.add(new Car("SUV", "Petrol"));30 carList.add(new Car("Sedan", "Diesel"));31 carList.add(new Car("Hatchback", "CNG"));32
33 Collections.sort(carList); // No comparator needed — uses compareTo()34
35 for (Car car : carList) {36 System.out.println(car);37 }38 }39}Output
1Hatchback (CNG)2Sedan (Diesel)3SUV (Petrol)(Sorted by carType: CNG < Diesel < Petrol — ascending lexicographic)
Step-by-Step Execution
Collections.sort(carList)is called without a Comparator.- Internally converts to array, calls
Arrays.sort(). - Since no Comparator provided, the algorithm casts each element to
Comparableand callscompareTo(). - Our
compareTocomparescarTypestrings lexicographically. - Elements reorder accordingly.
Key Difference: `compareTo` has ONE parameter
Because compareTo(T o) has only one parameter (o), the first object of comparison is always this — the object that owns the method. This means:
- You must implement
Comparableinside the class itself. - You can only define one natural ordering per class.
Why Comparable Limits Flexibility
1class Car implements Comparable<Car> {2 // This compareTo is FIXED — always sorts by carType ascending.3 // You CANNOT change this at call time.4 public int compareTo(Car other) {5 return this.carType.compareTo(other.carType);6 }7}If you now want to sort Car objects by carName, or in descending order — you cannot change compareTo without modifying the Car class. This is where Comparator shines.
String's Built-in `compareTo`
String also implements Comparable:
1"apple".compareTo("banana") // negative — apple < banana2"banana".compareTo("apple") // positive — banana > apple3"apple".compareTo("apple") // 0 — equalThis gives String a natural ordering that is lexicographic (dictionary order), which is why Collections.sort(list) on a List always sorts alphabetically by default.
11. Comparator vs Comparable Full Comparison
Side-by-Side Comparison
| Aspect | Comparator | Comparable |
|---|---|---|
| Package | java.util | java.lang |
| Interface type | Functional interface | Regular interface |
| Abstract method | compare(T o1, T o2) | compareTo(T o) |
| Number of parameters | 2 (two objects to compare) | 1 (compared to this) |
| Where implemented | External class / lambda | Inside the class itself |
| Modifies original class? | No | Yes |
| Multiple sorting strategies? | Yes (create many Comparators) | No (only one compareTo) |
| Can sort without modifying class? | Yes | No |
| Used with | Arrays.sort(arr, comparator), Collections.sort(list, comparator), PriorityQueue(comparator) | Arrays.sort(arr), Collections.sort(list) |
| Flexibility | High | Low |
When to Use Which
Mental Model
Comparable
= "I know how to compare myself to another object of my type." Comparator = "I am a third-party judge that knows how to compare two objects."
Complete Code Both Together
1import java.util.*;2
3// Car implements Comparable for its "natural" ordering (by carName, ascending)4class Car implements Comparable<Car> {5 String carName;6 String carType;7
8 Car(String carName, String carType) {9 this.carName = carName;10 this.carType = carType;11 }12
13 // Natural ordering: by carName, ascending14 @Override15 public int compareTo(Car other) {16 return this.carName.compareTo(other.carName);17 }18
19 @Override20 public String toString() {21 return carName + " (" + carType + ")";22 }23}24
25public class BothDemo {26 public static void main(String[] args) {27 List<Car> cars = new ArrayList<>();28 cars.add(new Car("SUV", "Petrol"));29 cars.add(new Car("Sedan", "Diesel"));30 cars.add(new Car("Hatchback", "CNG"));31
32 // 1. Using Comparable (natural order — by carName ascending)33 Collections.sort(cars);34 System.out.println("Natural order (Comparable):");35 cars.forEach(System.out::println);36
37 // 2. Using Comparator (by carType, descending)38 cars.sort((o1, o2) -> o2.carType.compareTo(o1.carType));39 System.out.println("\nBy carType descending (Comparator):");40 cars.forEach(System.out::println);41
42 // 3. Using Comparator (by carName, descending)43 cars.sort((o1, o2) -> o2.carName.compareTo(o1.carName));44 System.out.println("\nBy carName descending (Comparator):");45 cars.forEach(System.out::println);46 }47}Output
1Natural order (Comparable):2Hatchback (CNG)3Sedan (Diesel)4SUV (Petrol)5
6By carType descending (Comparator):7SUV (Petrol)8Sedan (Diesel)9Hatchback (CNG)10
11By carName descending (Comparator):12SUV (Petrol)13Sedan (Diesel)14Hatchback (CNG)Architecture Diagram
Common Mistakes
Mistake 1 Printing PriorityQueue Directly and Expecting Sorted Output
1PriorityQueue<Integer> pq = new PriorityQueue<>();2pq.add(5); pq.add(2); pq.add(8);3System.out.println(pq); // Prints [2, 5, 8] — this is the HEAP ARRAY, not sorted output!Fix: Use poll() in a loop to get sorted output.
Mistake 2 Sorting Custom Objects Without Comparator or Comparable
1Car[] cars = { new Car("SUV","Petrol"), new Car("Sedan","Diesel") };2Arrays.sort(cars); // ❌ ClassCastException at runtimeFix: Either implement Comparable in Car, or provide a Comparator.
Mistake 3 Expecting PriorityQueue to be FIFO
1PriorityQueue<Integer> pq = new PriorityQueue<>();2pq.add(10); pq.add(1); pq.add(5);3System.out.println(pq.poll()); // Prints 1, NOT 10 (min first, not insertion order)Fix: Understand that PriorityQueue is a min-heap by default. Use LinkedList or ArrayDeque for FIFO behavior.
Mistake 4 Integer Overflow in Comparator
1// Dangerous for large integers:2(a, b) -> a - b // Can overflow if a is large positive and b is large negativeFix: Use Integer.compare(a, b) instead of a - b for safety.
1Arrays.sort(arr, (a, b) -> Integer.compare(a, b)); // ascending, safe2Arrays.sort(arr, (a, b) -> Integer.compare(b, a)); // descending, safeBest Practices
- Prefer Comparator over Comparable when you need multiple sort strategies or when you can't modify the class.
- Implement Comparable only for the "natural" ordering of a class (e.g.,
Studentnaturally ordered by student ID). - Always use
Integer.compare(a, b)instead ofa - bin Comparators to avoid integer overflow. - Use lambda expressions for Comparators — they are concise and readable.
- Use
Comparator.comparing()from the Java 8 Comparator API for even cleaner code:
1 cars.sort(Comparator.comparing(car -> car.carName));2 cars.sort(Comparator.comparing((Car car) -> car.carName).reversed());- For DSA problems requiring heap: always use
PriorityQueue. Default = min-heap. Pass(a, b) -> b - afor max-heap.
12. Practice Questions
Easy
- Create a
PriorityQueue(min-heap), insert 10 random integers, and print them in ascending order usingpoll(). - What is the difference between
poll()andremove()in a Queue? - What does
peek()return when called on an emptyPriorityQueue? - Write a Comparator to sort
String[]in reverse alphabetical order. - What exception is thrown when you call
Arrays.sort()on an array of custom objects that don't implementComparable?
Medium
- Create a max-heap using
PriorityQueueand find the k-th largest element in an array. - Sort a list of
Employeeobjects (with fieldsnameandsalary) first bysalaryascending, then bynamealphabetically for ties. Use a Comparator. - Why does
System.out.println(priorityQueue)not print elements in sorted order? - Implement
Comparablein aBookclass so that books are sorted bypageCountascending. - When would you choose
ComparatoroverComparable? Give two scenarios.
Hard
- Implement a custom PriorityQueue that supports both min and max behavior by switching a flag — without using Java's built-in PriorityQueue comparator.
- You have a stream of integers. Using a
PriorityQueue, implement a running median finder. - What is the time complexity of building a
PriorityQueueof N elements one by one? Is there a more efficient approach? - Given a
PriorityQueuewhereCarhasmake,model, andyear— write a Comparator that sorts byyeardescending, thenmakeascending, thenmodelascending for ties. - Can a
Comparatorbe stateful? If yes, give an example where statefulness is useful.
13. Interview Notes
Frequently Asked Interview Questions
Q1: What is the difference between Comparator and Comparable?
Answer:
Comparableis injava.lang;Comparatoris injava.util.Comparabledefines the natural ordering of a class viacompareTo(T o)(one parameter — compared tothis).Comparatoris an external comparison strategy viacompare(T o1, T o2)(two parameters).Comparablemodifies the original class;Comparatordoes not.Comparableallows only one sort order per class;Comparatorallows unlimited sort strategies.
Q2: How does PriorityQueue work internally?
Answer: PriorityQueue uses a binary heap stored as an array. By default, it's a min-heap — the smallest element is always at the root (index 0). On add(), the element is inserted at the end and heapified upward. On poll(), the root is removed, the last element moves to the root, and the tree is heapified downward.
Q3: What is the default ordering in PriorityQueue?
Answer: Natural ordering — ascending for numbers, lexicographic for strings. Internally this is implemented as a min-heap.
Q4: How do you create a max-heap using PriorityQueue?
Answer:
1PriorityQueue<Integer> maxPQ = new PriorityQueue<>((a, b) -> b - a);2// or safely:3PriorityQueue<Integer> maxPQ = new PriorityQueue<>(Comparator.reverseOrder());Q5: What happens when you sort a custom object array without implementing Comparable?
Answer: A ClassCastException is thrown at runtime because the sorting algorithm tries to cast the object to Comparable to call compareTo(), but the class doesn't implement it.
Q6: What is the time complexity of `peek()` in PriorityQueue?
Answer: O(1) — the minimum (or maximum) element is always at index 0 of the internal array.
Q7: What is the time complexity of `add()` in PriorityQueue?
Answer: O(log N) — insertion goes to the end of the array and heapifies upward, which is O(log N) in the worst case.
Q8: Can you store `null` in a PriorityQueue?
Answer: No. PriorityQueue does not permit null elements and will throw a NullPointerException.
Q9: Is Queue thread-safe in Java?
Answer: PriorityQueue and LinkedList are not thread-safe. For thread-safe queues, use PriorityBlockingQueue, ConcurrentLinkedQueue, or ArrayBlockingQueue from java.util.concurrent.
Q10: What is the difference between `Queue` and `Deque`?
Answer: A Queue allows insertion at the rear and removal at the front (one-ended). A Deque (Double-Ended Queue) allows insertion and removal at both ends.
Tricky Points
PriorityQueue.poll()on an empty queue returnsnull.PriorityQueue.remove()on an empty queue throwsNoSuchElementException.- Printing a
PriorityQueuedirectly prints the heap array, not elements in sorted order. - The formula
a - bin a Comparator can cause integer overflow with extreme values. UseInteger.compare(a, b)instead. Comparatoris a functional interface (one abstract method);Comparableis not annotated as@FunctionalInterfacebut also has only one abstract method.Collections.sort()internally callsArrays.sort()after converting the list to an array.
14. Summary Revision Bullets
Queue
Queueis an interface, child ofCollection, grandchild ofIterable.- Generally follows FIFO, but
PriorityQueueis an exception. - Six methods in three pairs: insert (
add/offer), remove-head (remove/poll), inspect-head (element/peek). - The first method in each pair throws an exception on failure; the second returns
nullorfalse.
PriorityQueue
- Implements
Queueusing an internal binary heap. - Default: min-heap (natural ordering, ascending for numbers).
- To get max-heap: pass
(a, b) -> b - aorComparator.reverseOrder()to constructor. peek()= O(1),add()/poll()= O(log N), arbitraryremove(o)= O(N).- Never use PriorityQueue when you need FIFO — use
LinkedListorArrayDeque. - Use PriorityQueue for DSA heap problems in Java.
Comparator
- External comparison strategy — does not modify the class being compared.
- Functional interface with
int compare(T o1, T o2). - Returns: positive → swap, zero → equal, negative → no swap.
val1 - val2= ascending;val2 - val1= descending.- Allows multiple sort strategies for the same class.
- Can be provided as lambda, anonymous class, or named class.
- Passed to:
Arrays.sort(arr, cmp),Collections.sort(list, cmp),new PriorityQueue<>(cmp).
Comparable
- Natural ordering defined inside the class.
- Interface with
int compareTo(T o)— one parameter (compared tothis). Integer,String,Double, etc. all implementComparable.- Implementing
ComparableenablesArrays.sort(arr)andCollections.sort(list)without a Comparator. - Only one sort order possible per class.
- Must modify the original class.
Comparator vs Comparable
| Comparator | Comparable | |
|---|---|---|
| Where? | External | Inside class |
| Parameters | 2 | 1 (this + 1) |
| Sort strategies | Many | One |
| Modify class? | No | Yes |
End of Chapter — Queue, PriorityQueue, Comparator & Comparable
Mastery check
How well can you recall this?
Finished this lesson?