Java BlockingDeque remove()方法及示例

Java BlockingDeque remove()方法及示例

BlockingDequeremove() 方法会删除Deque容器的头部。如果Deque容器是空的,该方法会抛出一个NoSuchElementException。如果在参数中传递了一个元素,如果Deque中存在该元素,它就会将其删除。

语法

public E remove() or boolean remove(element)

参数: 该方法接受一个临时参数元素,该元素将被从BlockingDeque中删除。

返回: 如果参数被传递,该方法返回真或假,否则不返回。如果该元素在Deque中存在,则返回真,否则返回假。

异常 :如果Deque是空的,该函数会抛出一个NoSuchElementException。

注意BlockingDequeremove() 方法是从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()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程