📜  Java中的 PriorityBlockingQueue peek() 方法

📅  最后修改于: 2022-05-13 01:55:13.941000             🧑  作者: Mango

Java中的 PriorityBlockingQueue peek() 方法

PriorityBlockingQueue 的peek()方法返回PriorityBlockingQueue头部的元素。它检索 LinkedBlockingQueue 头部的值,但不删除它。如果 PriorityBlockingQueue 不包含任何元素,则此方法返回 null。 PriorityBlockingQueue 队列使用与类 PriorityQueue 相同的排序规则。

句法:

public E peek()

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

返回:此方法返回 PriorityBlockingQueue 的头部

下面的程序说明了 PriorityBlockingQueue 的 peek() 方法。

示例 1:

// Java Program Demonstrate peek()
// method of PriorityBlockingQueue
  
import java.util.concurrent.PriorityBlockingQueue;
  
public class GFG {
    public static void main(String[] args)
    {
        // define capacity of PriorityBlockingQueue
        int capacityOfQueue = 5;
  
        // create object of PriorityBlockingQueue
        PriorityBlockingQueue PrioQueue
            = new PriorityBlockingQueue(capacityOfQueue);
  
        // Add elements to PriorityBlockingQueue
        PrioQueue.add(464161);
        PrioQueue.add(416165);
  
        // print PrioQueue
        System.out.println("PrioQueue: " + PrioQueue);
  
        // get head of PriorityBlockingQueue
        int head = PrioQueue.peek();
  
        // print head of PriorityBlockingQueue
        System.out.println("Head of Queue: " + head);
    }
}
输出:
PrioQueue: [416165, 464161]
Head of Queue: 416165

示例 2:说明包含名称列表的 PriorityBlockingQueue 的 peek() 方法。

// Java Program Demonstrate peek()
// method of PriorityBlockingQueue
  
import java.util.concurrent.PriorityBlockingQueue;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // define capacity of PriorityBlockingQueue
        int capacityOfQueue = 5;
  
        // create object of PriorityBlockingQueue 
        PriorityBlockingQueue names
            = new PriorityBlockingQueue(capacityOfQueue);
  
        // Add names of students of girls college
        names.add("Geeks");
        names.add("forGeeks");
        names.add("A");
        names.add("Computer");
        names.add("Portal");
  
        // print PrioQueue
        System.out.println("List of Names: " + names.toString());
  
        // get head of PriorityBlockingQueue
        String head = names.peek();
  
        // print head of PriorityBlockingQueue
        System.out.println("Head of Queue: " + head);
  
        // remove one name from head
        names.poll();
        System.out.println("First Name from head is removed");
  
        // print PrioQueue
        System.out.println("List of Names: " + names.toString());
  
        // get head of PriorityBlockingQueue
        head = names.peek();
  
        // print head of PriorityBlockingQueue
        System.out.println("Head of Queue: " + head);
    }
}
输出:
List of Names: [A, Computer, Geeks, forGeeks, Portal]
Head of Queue: A
First Name from head is removed
List of Names: [Computer, Portal, Geeks, forGeeks]
Head of Queue: Computer

参考:
https://docs.oracle.com/javase/8/docs/api/java Java