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


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


Java.util.TreeSet.contains()方法用於檢查TreeSet中是否存在特定元素。因此,本質上,它用於檢查TreeSet是否包含任何特定元素。

用法:

Tree_Set.contains(Object element)

參數:參數element 是TreeSet的類型。如果TreeSet中不存在此元素,則需要對其進行檢查。


返回值:如果元素存在於集合中,則該方法返回true,否則返回False。

以下示例程序旨在說明Java.util.TreeSet.conatins()方法:

// Java code to illustrate contains() method 
import java.io.*; 
import java.util.TreeSet; 
  
public class TreeSetDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty TreeSet 
        TreeSet<String> tree = new TreeSet<String>(); 
  
        // Use add() method to add elements into the Set 
        tree.add("Welcome"); 
        tree.add("To"); 
        tree.add("Geeks"); 
        tree.add("4"); 
        tree.add("Geeks"); 
        tree.add("TreeSet"); 
  
        // Displaying the TreeSet 
        System.out.println("TreeSet: " + tree); 
  
        // Check for "TreeSet" in the set 
        System.out.println("Does the Set contains 'TreeSet'? " +  
                                           tree.contains("TreeSet")); 
  
        // Check for "4" in the set 
        System.out.println("Does the Set contains '4'? " +  
                                             tree.contains("4")); 
  
        // Check if the list contains "No" 
        System.out.println("Does the Set contains 'No'? " +  
                                             tree.contains("No")); 
    } 
}
輸出:
TreeSet: [4, Geeks, To, TreeSet, Welcome]
Does the Set contains 'TreeSet'? true
Does the Set contains '4'? true
Does the Set contains 'No'? false


相關用法


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