Comparable<T>.compareTo()) is given highest priority and dequeued first.1 has higher priority than 5.
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(5);
pq.add(1);
pq.add(3);
System.out.println(pq.poll()); // Outputs 1
Comparator when constructing the queue.
PriorityQueue<String> pq = new PriorityQueue<>(Comparator.reverseOrder());
pq.add("Apple");
pq.add("Banana");
pq.add("Cherry");
System.out.println(pq.poll()); // Outputs "Cherry"
iterator() does not return elements in priority order.poll()): \(O(\log n)\)peek()): \(O(1)\)
A diagram showing the heap structure of a PriorityQueue
When used in a generic class or method, T[] indicates an array of generic elements:
public class Box<T> {
private T[] items;
public void setItems(T[] items) {
this.items = items;
}
public T getFirstItem() {
return items[0];
}
}
Here:
T can be any reference type like String, Integer, MyClass, etc.new T[] directly due to type erasure. You often need to pass in an array or use Array.newInstance() via reflection.
You cannot use T[] with primitive types like int, char, double directly in a generic context:
publicvoid printArray(T[] array) { for (T element : array) { System.out.println(element); } }
String[] strings = {"Java", "GPT"};
printArray(strings); // Works
int[] nums = {1, 2, 3};
printArray(nums); // Error: incompatible types
| Syntax | Meaning | Works with Primitives? |
|---|---|---|
T[] |
Array of generic or reference type T |
❌ Not for primitives |
String[] |
Array of String objects |
✅ |
int[] |
Array of primitives | ✅ but not with generics |