Java Set contains()方法及实例

Java Set contains()方法及实例

Java.util.Set.contains()方法是用来检查一个特定的元素是否存在于Set中。所以基本上它是用来检查一个Set是否包含任何特定的元素。

语法

boolean contains(Object element)

参数: 参数元素的类型为集合。这是需要测试的元素,如果它在集合中存在或不存在。

返回值: 如果该元素存在于集合中,该方法返回true,否则返回False。

下面的程序说明了Java.util.Set.contains()方法。

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

输出。

Set: [4, Geeks, Welcome, To]
Does the Set contains 'Geeks'? true
Does the Set contains '4'? true
Does the Set contains 'No'? false

参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#contains(java.lang.Object)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程