Java PriorityQueue offer()用法及代码示例 您所在的位置:网站首页 java队列offer Java PriorityQueue offer()用法及代码示例

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

2023-11-15 02:06| 来源: 网络整理| 查看: 265

java.util.PriorityQueue.offer()方法用于将特定元素插入优先级队列。它的行为类似于优先级队列的add()方法。

用法:

Priority_Queue.offer(Object element)

参数:参数element 的类型为PriorityQueue,是指要插入到Queue中的元素。

返回值:如果将值成功插入队列,则该方法返回True。

异常:该方法可以引发两种类型的异常:

NullPointerException:如果要插入的元素为NULL。 ClassCastException:如果要插入的元素是其他类型,无法与Queue的现有元素进行比较。

以下示例程序旨在说明java.util.PriorityQueue.offer()方法 示例1:

// Java code to illustrate offer() 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("4");         queue.add("Geeks");            // Displaying the PriorityQueue         System.out.println("Initial PriorityQueue: " + queue);            // Inserting using offer()         queue.offer("The");         queue.offer("Priority");         queue.offer("Class");            // Displaying th final Queue         System.out.println("Priority queue after Insertion: " + queue);     } } 输出: Initial PriorityQueue: [4, Geeks, To, Welcome, Geeks] Priority queue after Insertion: [4, Class, Priority, Geeks, Geeks, To, The, Welcome]

示例2:

// Java code to illustrate offer() 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);            // Inserting using offer()         queue.offer(100);         queue.offer(120);         queue.offer(150);            // Displaying th final Queue         System.out.println("Priority queue after Insertion: " + queue);     } } 输出: Initial PriorityQueue: [5, 10, 30, 20, 15] Priority queue after Insertion: [5, 10, 30, 20, 15, 100, 120, 150]



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有