当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java PriorityQueue peek()用法及代码示例


Java中的java.util.PriorityQueue.peek()方法用于检索或获取Queue的第一个元素或出现在Queue头的元素。检索到的元素不会从队列中删除或删除。

用法:

Priority_Queue.peek()

参数:该方法不带任何参数。


返回值:该方法返回Queue开头的元素,如果Queue为空,则返回NULL。

下面的程序演示了java.util.PriorityQueue.peek()方法:
示例1:

// Java code to illustrate peek() 
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 the element at the head of the queue 
        System.out.println("The element at the head of the"
                           + " queue is: " + queue.peek()); 
  
        // 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: [For, Geeks, To, Welcome, Geeks]

示例2:

// Java code to illustrate peek() 
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.peek()); 
  
        // 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: [5, 10, 30, 20, 15]


相关用法


注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 PriorityQueue peek() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。