Java : Priority Queue

前端 未结 3 1612
情深已故
情深已故 2021-01-18 05:41

I have a java program which goes like this

public class PriorityQueueExample {

public static void main(String[] args) {
    PriorityQueue

        
3条回答
  •  盖世英雄少女心
    2021-01-18 06:23

    poll() and remove() will give sorted order not peek() as per java8.

     PriorityQueue pq = new PriorityQueue();
        pq.add(10);
        pq.add(1);
        pq.add(9);
        pq.add(2);
        pq.add(8);
        pq.add(3);
        pq.add(7);
        pq.add(4);
        pq.add(6);
        pq.add(5);
            // Remove items from the Priority Queue (DEQUEUE)
            while (!pq.isEmpty()) {
              //  System.out.println(pq.remove());
              System.out.println(pq.poll());
            }
    Output for poll() & remove():
    1 
    2
    3 
    4 
    5 
    6 
    7 
    8 
    9 
    10
    output for peek():
    1
    1
    1
    1
    1
    1
    1
    1
    1
    1
    

提交回复
热议问题