How does Java's PriorityQueue differ from a min-heap?
Solution 1:
The default PriorityQueue is implemented with Min-Heap, that is the top element is the minimum one in the heap.
In order to implement a max-heap, you can create your own Comparator:
import java.util.Comparator;
public class MyComparator implements Comparator<Integer>
{
public int compare( Integer x, Integer y )
{
return y - x;
}
}
So, you can create a min-heap and max-heap in the following way:
PriorityQueue minHeap=new PriorityQueue();
PriorityQueue maxHeap=new PriorityQueue(size, new MyComparator());
Solution 2:
For max-heap you can use:
PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
Solution 3:
Add() works like an insertWithPriority.
You can define priority for the type that you want using the constructor:
PriorityQueue(int, java.util.Comparator)
look under https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/PriorityQueue.html
The order the Comparator gives will represent the priority in the queue.
Solution 4:
From the PriorityQueue
JavaDocs:
An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering, or by a
Comparator
provided at queue construction time, depending on which constructor is used.
Priority is meant to be an inherent property of the objects in the queue. The elements are ordered based on some sort of comparison. To insert some object with a given priority, you would just set whatever field(s) on the object affect the ordering, and add()
it.
And, as @Daniel commented,
Generally Java Objects are named based on the functionality they provide, not named based on how they are implemented.