java 队列 peek_Java中的PriorityQueue peek() 方法 - Break易站

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

句法:

Priority_Queue.peek()

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

返回值:该方法返回队列头部的元素,如果队列为空,则返回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 queue = new PriorityQueue();

// 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 queue = new PriorityQueue();

// 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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值