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


Java PriorityBlockingQueue remove()用法及代碼示例


PriorityBlockingQueue的remove(Object o)方法用於從此隊列中刪除元素。如果存在,此方法將刪除作為參數傳遞的元素的單個實例。
當且僅當元素被刪除時,它才返回true;否則,它返回false。

用法:

public boolean remove(Object o)

參數:此方法接受必需參數o,該參數是要從此隊列中刪除的元素(如果存在)。


返回值:如果指定的元素已成功刪除,則此方法返回true。否則,此方法返回false。

下麵的程序說明PriorityBlockingQueue中的remove()方法:

示例1:

// Java Program Demonstrate remove() 
// method of PriorityBlockingQueue 
  
import java.util.concurrent.PriorityBlockingQueue; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create object of PriorityBlockingQueue 
        PriorityBlockingQueue<Integer> pbq 
            = new PriorityBlockingQueue<Integer>(); 
  
        // Add element to PriorityBlockingQueue 
        pbq.put(1); 
        pbq.put(2); 
        pbq.put(3); 
        pbq.put(4); 
  
        // print queue 
        System.out.println("Queue: " + pbq); 
  
        // remove 2 
        boolean res = pbq.remove(2); 
        System.out.println("\n2 removed: " + res); 
  
        // print queue 
        System.out.println("Queue:  " + pbq); 
  
        // remove 5 
        res = pbq.remove(5); 
        System.out.println("\n5 removed: " + res); 
  
        // print queue 
        System.out.println("Queue:  " + pbq); 
    } 
}
輸出:
Queue: [1, 2, 3, 4]

2 removed: true
Queue:  [1, 4, 3]

5 removed: false
Queue:  [1, 4, 3]
// Java Program Demonstrate remove() 
// method of PriorityBlockingQueue 
  
import java.util.concurrent.PriorityBlockingQueue; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // create object of PriorityBlockingQueue 
        PriorityBlockingQueue<String> pbq 
            = new PriorityBlockingQueue<String>(); 
  
        // Add element to PriorityBlockingQueue 
        pbq.put("Geeks"); 
        pbq.put("forGeeks"); 
        pbq.put("A Computer"); 
        pbq.put("Portal"); 
  
        // print queue 
        System.out.println("Queue: " + pbq); 
  
        // remove Geeks 
        boolean res = pbq.remove("Geeks"); 
        System.out.println("\nGeeks removed: " + res); 
  
        // print queue 
        System.out.println("Queue:  " + pbq); 
  
        // remove SandeepJain 
        res = pbq.remove("SandeepJain"); 
        System.out.println("\nSandeepJain removed: " + res); 
  
        // print queue 
        System.out.println("Queue:  " + pbq); 
    } 
}
輸出:
Queue: [A Computer, Portal, Geeks, forGeeks]

Geeks removed: true
Queue:  [A Computer, Portal, forGeeks]

SandeepJain removed: false
Queue:  [A Computer, Portal, forGeeks]


相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 PriorityBlockingQueue remove() method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。