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


Java BlockingQueue contains()用法及代碼示例


BlockingQueue接口的contains(Object o)方法檢查容器中是否存在參數中傳遞的元素。如果該元素存在於容器中,則返回true,否則返回false值。

用法:

public boolean contains(Object o)

參數:此方法接受一個強製性參數o,該參數要檢查容器中是否存在容器。


返回值:如果該元素存在,則此方法返回true,否則返回false。

注意:BlockingQueue的contains()方法已從Java中的Queue類繼承。

下麵的程序說明BlockingQueue的contains()方法:

示例1:

// 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<Integer> BQ 
            = new LinkedBlockingQueue<Integer>(); 
  
        // 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

示例2:

// 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<String> BQ 
            = new LinkedBlockingQueue<String>(); 
  
        // 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://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedBlockingQueue.html#contains(java.lang.Object)



相關用法


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