How does Java's PriorityQueue differ from a min-heap?

前端 未结 6 1918
时光取名叫无心
时光取名叫无心 2021-01-30 00:44

Why did they name PriorityQueue if you can\'t insertWithPriority? It seems very similar to a heap. Are there any differences? If no difference, the

6条回答
  •  北海茫月
    2021-01-30 01:28

    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
    {
        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());
    

提交回复
热议问题