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


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


如果此集合包含指定的元素,則使用java.util.LinkedHashSet類的contains()方法返回true,否則返回false。

用法:

public boolean contains(Object o)

參數:此方法將元素o作為參數,要測試其是否存在於此集中。


返回值:如果此集合包含指定的元素,則此方法返回true。

以下示例說明了contains()方法。

示例1:

// Java program to demonstrate 
// contains() method 
// for String value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) throws Exception 
    { 
        try { 
  
            // Create the object of LinkedHashSet<String> 
            LinkedHashSet<String> 
                linkset = new LinkedHashSet<String>(); 
  
            // populate hash set 
            linkset.add("A"); 
            linkset.add("B"); 
            linkset.add("C"); 
  
            // print the LinkedHashSet 
            System.out.println("LinkedHashSet: "
                               + linkset); 
  
            // check the existence of element 
            // using method contains() 
            boolean exist = linkset.contains("C"); 
  
            // print the result 
            System.out.println("Is the element"
                               + " 'C' present: "
                               + exist); 
        } 
  
        catch (NullPointerException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
LinkedHashSet: [A, B, C]
Is the element 'C' present: true

示例2:

// Java program to demonstrate 
// contains() method 
// for Integer value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) throws Exception 
    { 
        try { 
  
            // Create the object of LinkedHashSet<Integer> 
            LinkedHashSet<Integer> 
                linkset = new LinkedHashSet<Integer>(); 
  
            // populate hash set 
            linkset.add(10); 
            linkset.add(20); 
            linkset.add(30); 
  
            // print the LinkedHashSet 
            System.out.println("LinkedHashSet: "
                               + linkset); 
  
            // check the existence of element 
            // using method contains() 
            boolean exist = linkset.contains(25); 
  
            // print the result 
            System.out.println("Is the element"
                               + " '25' present: "
                               + exist); 
        } 
  
        catch (NullPointerException e) { 
            System.out.println("Exception thrown : " + e); 
        } 
    } 
}
輸出:
LinkedHashSet: [10, 20, 30]
Is the element '25' present: false


相關用法


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