Java BlockingDeque removeFirstOccurrence()方法及示例
BlockingDeque 的 removeFirstOccurrence() 方法会从这个deque中删除第一次出现的指定元素。如果该deque不包含该元素,它将保持不变。如果这个deque包含指定的元素,则返回true,否则返回false。
语法
public boolean removeFirstOccurrence(Object o)
参数: 该方法接受一个强制性参数 o ,它指定了要从Deque容器中删除的元素。
返回: 如果该元素存在并从Deque容器中删除,该方法返回 true ,否则返回 false
注意 : BlockingDeque 的 removeFirstOccurrence() 方法继承自Java中的LinkedBlockingDeque类。
以下程序说明了BlockingDeque的removeFirstOccurrence()方法。
程序1: 当元素存在时
// Java Program to demonstrate removeFirstOccurrence()
// 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(15);
BD.add(20);
BD.add(20);
BD.add(15);
// print Deque
System.out.println("Blocking Deque: " + BD);
if (BD.removeFirstOccurrence(15))
System.out.println("First occurrence of 15 removed");
else
System.out.println("15 not present and not removed");
// prints the Deque after removal
System.out.println("Blocking Deque: " + BD);
}
}
输出
Blocking Deque: [15, 20, 20, 15]
First occurrence of 15 removed
Blocking Deque: [20, 20, 15]
程序2: 当元素不存在时
// Java Program to demonstrate removeFirstOccurrence()
// 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(15);
BD.add(20);
BD.add(20);
BD.add(15);
// print Deque
System.out.println("Blocking Deque: " + BD);
if (BD.removeFirstOccurrence(10))
System.out.println("First occurrence of 10 removed");
else
System.out.println("10 not present and not removed");
// prints the Deque after removal
System.out.println("Blocking Deque: " + BD);
}
}
输出
Blocking Deque: [15, 20, 20, 15]
10 not present and not removed
Blocking Deque: [15, 20, 20, 15]
参考资料: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/BlockingDeque.html#removeFirstOccurrence(java.lang.Object)