Why did they name PriorityQueue
if you can't insertWithPriority? It seems very similar to a heap. Are there any differences? If no difference, then why was it named PriorityQueue
and not Heap?
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());