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


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