📌  相关文章
📜  Java中的 BlockingDeque remove() 方法及示例

📅  最后修改于: 2022-05-13 01:54:27.324000             🧑  作者: Mango

Java中的 BlockingDeque remove() 方法及示例

BlockingDequeremove()方法移除了 Deque 容器的头部。如果 Deque 容器为空,该方法将引发NoSuchElementException 。如果在参数中传递了一个元素,它会删除给定元素(如果存在于双端队列中)。

句法:

public E remove() or boolean remove(element)

参数:此方法接受要从 BlockingDeque 中删除的临时参数元素

返回:如果传递了参数,此方法返回真或假,否则不返回任何内容。如果元素在 Deque 中,则返回 true,否则返回 false。

异常:如果双端队列为空,该函数将抛出NoSuchElementException

注意BlockingDequeremove()方法继承自Java中的 LinkedBlockingDeque 类。

下面的程序说明了 BlockingDeque 的 remove() 方法:

方案一:

// 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 BD
            = new LinkedBlockingDeque();
  
        // 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]

方案二:

// 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 BD
            = new LinkedBlockingDeque();
  
        // 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: Java/util/concurrent/BlockingDeque.html#remove()