Java中的java.util.PriorityQueue.poll()方法用于检索或获取和删除队列的第一个元素或队列头部的元素。peek()方法只检索的元件在头部但poll() 也与检索移除element。如果队列为空,则返回NULL。

句法:

Priority_Queue.poll()

参数:该方法不接受任何参数。

返回值:该方法返回队列头部的元素,如果队列为空,则返回NULL。

下面的程序说明了java.util.PriorityQueue.poll()方法的使用

程序1:

// Java code to illustrate poll()
import java.util.*;

public class PriorityQueueDemo {
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue
        PriorityQueue<String> queue = new PriorityQueue<String>();

        // Use add() method to add elements into the Queue
        queue.add("Welcome");
        queue.add("To");
        queue.add("Geeks");
        queue.add("For");
        queue.add("Geeks");

        // Displaying the PriorityQueue
        System.out.println("Initial PriorityQueue: " + queue);

        // Fetching and removing the element at the head of the queue
        System.out.println("The element at the head of the"
                           + " queue is: " + queue.poll());

        // Displaying the Queue after the Operation
        System.out.println("Final PriorityQueue: " + queue);
    }
}

输出:

Initial PriorityQueue: [For, Geeks, To, Welcome, Geeks]
The element at the head of the queue is: For
Final PriorityQueue: [Geeks, Geeks, To, Welcome]

程序2:

// Java code to illustrate poll()
import java.util.*;

public class PriorityQueueDemo {
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue
        PriorityQueue<Integer> queue = new PriorityQueue<Integer>();

        // Use add() method to add elements into the Queue
        queue.add(10);
        queue.add(15);
        queue.add(30);
        queue.add(20);
        queue.add(5);

        // Displaying the PriorityQueue
        System.out.println("Initial PriorityQueue: " + queue);

        // Fetching the element at the head of the queue
        System.out.println("The element at the head of the"
                           + " queue is: " + queue.poll());

        // Displaying the Queue after the Operation
        System.out.println("Final PriorityQueue: " + queue);
    }
}

输出:

Initial PriorityQueue: [5, 10, 30, 20, 15]
The element at the head of the queue is: 5
Final PriorityQueue: [10, 15, 30, 20]

 
转载请保留页面地址:https://www.breakyizhan.com/java/5364.html
扫描二维码添加微信 
  • ,每次淘宝领取淘宝优惠券,淘宝购物更优惠。现在添加微信,还可以领取机械键盘50元优惠券!添加微信后回复机械键盘即可领取!
    支持我们,就用微信淘宝!