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


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


Java.util.PriorityQueue.remove()方法用于从PriorityQueue中删除特定元素。

用法:

Priority_Queue.remove(Object O)

参数:参数O是PriorityQueue的类型,并指定要从PriorityQueue中删除的元素。


返回值:如果队列中存在指定的元素,则此方法返回True,否则返回False。

以下示例程序旨在说明Java.util.PriorityQueue.remove()方法:

// Java code to illustrate remove() 
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); 
  
        // Removing elements using remove() method 
        queue.remove("Geeks"); 
        queue.remove("For"); 
        queue.remove("Welcome"); 
  
        // Displaying the PriorityQueue after removal 
        System.out.println("PriorityQueue after removing "
                           + "elements: " + queue); 
    } 
}
输出:
Initial PriorityQueue: [For, Geeks, To, Welcome, Geeks]
PriorityQueue after removing elements: [Geeks, To]

示例2:

// Java code to illustrate remove() 
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); 
  
        // Removing elements using remove() method 
        queue.remove(30); 
        queue.remove(5); 
  
        // Displaying the PriorityQueue after removal 
        System.out.println("PriorityQueue after removing "
                           + "elements: " + queue); 
    } 
}
输出:
Initial PriorityQueue: [5, 10, 30, 20, 15]
PriorityQueue after removing elements: [10, 20, 15]


相关用法


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