當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。