在 Java 中使用 contains() 方法判断 Set 集合中是否包含某元素

在 Java 中使用 contains() 方法判断 Set 集合中是否包含某元素

Java.util.Set.contains() 方法用于检查 Set 是否包含特定元素。因此,它主要用于检查 Set 是否包含任何特定元素。

语法:

boolean contains(Object element)

参数: 参数 element 是 Set 类型的元素。这是要测试其是否存在于集合中的元素。

返回值: 方法如果集合中存在该元素,则返回 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教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程