Creating a PriorityQueue with Natural Ordering
You'll learn how to instantiate a PriorityQueue that automatically orders elements using their natural comparison rules.
What Is Natural Ordering?
When you create a PriorityQueue without specifying a custom comparator, it relies on the natural ordering of elements. This means the elements must implement the Comparable interface, which defines how they compare to each other. Types like Integer, String, Double, and Character already have natural ordering built in.
Think of it like organizing books: if you don't tell someone how to sort them, they'll use the most obvious method—alphabetically by title. Similarly, integers naturally order from smallest to largest, and strings order alphabetically.
Creating a PriorityQueue with Natural Ordering
import java.util.PriorityQueue;
public class NaturalOrderingExample {
public static void main(String[] args) {
// PriorityQueue of integers (smallest comes first)
PriorityQueue<Integer> numbers = new PriorityQueue<>();
numbers.offer(15);
numbers.offer(5);
numbers.offer(10);
System.out.println(numbers.poll()); // 5
System.out.println(numbers.poll()); // 10
System.out.println(numbers.poll()); // 15
// PriorityQueue of strings (alphabetical order)
PriorityQueue<String> words = new PriorityQueue<>();
words.offer("banana");
words.offer("apple");
words.offer("cherry");
System.out.println(words.poll()); // apple
System.out.println(words.poll()); // banana
System.out.println(words.poll()); // cherry
}
}
Notice you don't pass anything to the constructor—the PriorityQueue automatically uses each element's compareTo method. For integers, smaller numbers have higher priority. For strings, earlier alphabetical entries come first.
Key Takeaway: Creating a PriorityQueue with new PriorityQueue<>() uses natural ordering, requiring elements to be Comparable—integers prioritize smallest first, strings prioritize alphabetically.