当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。