Java中的 BlockingQueue contains() 方法及示例
BlockingQueue接口的contains(Object o)方法检查参数中传递的元素是否存在于容器中。如果元素存在于容器中,则返回 true,否则返回 false 值。
句法:
public boolean contains(Object o)
参数:此方法接受一个强制参数o ,它在容器中的存在将在容器中检查。
返回:如果元素存在,此方法返回 true,否则返回 false。
注意: BlockingQueue的contains()方法继承自Java中的Queue类。
下面的程序说明了 BlockingQueue 的 contains() 方法:
方案一:
// Java Program Demonstrate contains()
// method of BlockingQueue
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of BlockingQueue
BlockingQueue BQ
= new LinkedBlockingQueue();
// Add numbers to end of BlockingQueue
BQ.add(10);
BQ.add(20);
BQ.add(30);
BQ.add(40);
// before removing print queue
System.out.println("Blocking Queue: " + BQ);
// check for presence using function
if (BQ.contains(10)) {
System.out.println("Blocking Queue contains 10");
}
else {
System.out.println("Blocking Queue does not contain 10");
}
}
}
输出:
Blocking Queue: [10, 20, 30, 40]
Blocking Queue contains 10
方案二:
// Java Program Demonstrate contains()
// method of BlockingQueue
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.*;
public class GFG {
public static void main(String[] args)
throws IllegalStateException
{
// create object of BlockingQueue
BlockingQueue BQ
= new LinkedBlockingQueue();
// Add numbers to end of BlockingQueue
BQ.add("ab");
BQ.add("cd");
BQ.add("fg");
BQ.add("xz");
// before removing print queue
System.out.println("Blocking Queue: " + BQ);
// check for presence using function
if (BQ.contains("go")) {
System.out.println("Blocking Queue contains 'go'");
}
else {
System.out.println("Blocking Queue does not contain 'go'");
}
}
}
输出:
Blocking Queue: [ab, cd, fg, xz]
Blocking Queue does not contain 'go'
参考: https: Java Java.lang.Object)