Change priorityQueue to max priorityqueue

后端 未结 17 1831
一整个雨季
一整个雨季 2020-12-04 05:13

I have priority queue in Java of Integers:

 PriorityQueue pq= new PriorityQueue();

When I call pq.poll(

17条回答
  •  一向
    一向 (楼主)
    2020-12-04 06:14

    The elements of the priority queue are ordered according to their natural ordering, or by a Comparator provided at queue construction time.

    The Comparator should override the compare method.

    int compare(T o1, T o2)
    

    Default compare method returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

    The Default PriorityQueue provided by Java is Min-Heap, If you want a max heap following is the code

    public class Sample {
        public static void main(String[] args) {
            PriorityQueue q = new PriorityQueue(new Comparator() {
    
                public int compare(Integer lhs, Integer rhs) {
                    if(lhsrhs) return -1;
                    return 0;
                }
            });
            q.add(13);
            q.add(4);q.add(14);q.add(-4);q.add(1);
            while (!q.isEmpty()) {
                System.out.println(q.poll());
            }
        }
    
    }
    

    Reference :https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#comparator()

提交回复
热议问题