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


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


BlockingDeque的remove()方法刪除了Deque容器的頭部。如果Deque容器為空,則此方法引發NoSuchElementException。如果在參數中傳遞了元素,則它將刪除給定元素(如果存在於雙端隊列中)。

用法:

public E remove() or boolean remove(element)

參數:此方法接受一個臨時參數element ,該元素將從BlockingDeque中刪除


返回值:如果傳遞了參數,則此方法返回true或false,否則不返回任何內容。如果元素在雙端隊列中存在,則返回true,否則返回false。

異常:如果Deque為空,則該函數將引發NoSuchElementException。

注意:BlockingDeque的remove()方法已從Java中的LinkedBlockingDeque類繼承。

以下示例程序旨在說明BlockingDeque的remove()方法:

示例1:

// Java Program Demonstrate remove() 
// method of BlockingDeque 
  
import java.util.concurrent.LinkedBlockingDeque; 
import java.util.concurrent.BlockingDeque; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
        throws InterruptedException 
    { 
  
        // create object of BlockingDeque 
        BlockingDeque<Integer> BD 
            = new LinkedBlockingDeque<Integer>(); 
  
        // Add numbers to end of BlockingDeque 
        BD.add(7855642); 
        BD.add(35658786); 
        BD.add(5278367); 
        BD.add(74381793); 
  
        // print Deque 
        System.out.println("Blocking Deque: " + BD); 
  
        // removes the front element 
        BD.remove(); 
        System.out.println("Blocking Deque: " + BD); 
  
        // removes the element 
        BD.remove(5278367); 
        System.out.println("Blocking Deque: " + BD); 
    } 
}
輸出:
Blocking Deque: [7855642, 35658786, 5278367, 74381793]
Blocking Deque: [35658786, 5278367, 74381793]
Blocking Deque: [35658786, 74381793]

示例2:

// Java Program Demonstrate remove() 
// method of BlockingDeque 
  
import java.util.concurrent.LinkedBlockingDeque; 
import java.util.concurrent.BlockingDeque; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
        throws InterruptedException 
    { 
  
        // create object of BlockingDeque 
        BlockingDeque<Integer> BD 
            = new LinkedBlockingDeque<Integer>(); 
  
        // Add numbers to end of BlockingDeque 
        BD.add(7855642); 
        BD.add(35658786); 
        BD.add(5278367); 
        BD.add(74381793); 
  
        // print Deque 
        System.out.println("Blocking Deque: " + BD); 
  
        BD.clear(); 
  
        // removes the front element 
        BD.remove(); 
        System.out.println("Blocking Deque: " + BD); 
  
        // removes the element 
        BD.remove(5278367); 
        System.out.println("Blocking Deque: " + BD); 
    } 
}

輸出:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.concurrent.LinkedBlockingDeque.removeFirst(LinkedBlockingDeque.java:453)
    at java.util.concurrent.LinkedBlockingDeque.remove(LinkedBlockingDeque.java:672)
    at GFG.main(GFG.java:29)

參考: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingDeque.html#remove()



相關用法


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