Java AbstractSet的contains()方法及示例

Java AbstractSet的contains()方法及示例

Java AbstractSet的contains()方法是用来检查一个元素是否存在于一个集合中。它以元素为参数,如果该元素存在于集合中,则返回True。

语法

public boolean contains(Object element)

参数: 参数元素的类型是集合。这个参数指的是需要在集合中检查其出现的元素。

返回值: 该方法返回一个布尔值。如果元素存在于集合中,它返回True,否则返回False。

下面的程序说明了AbstractSet.contains()方法。

程序1 :

// Java code to illustrate
// AbstractSet.contains()
  
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Creating an empty set
        AbstractSet<String>
            abs = new TreeSet<String>();
  
        // Use add() method to add
        // elements in the set
        abs.add("Geeks");
        abs.add("for");
        abs.add("Geeks");
        abs.add("10");
        abs.add("20");
  
        // Displaying the set
        System.out.println("AbstractSet: "
                           + abs);
  
        // Check if the set contains "Hello"
        System.out.println("\nDoes the set"
                           + " contains 'Hello': "
                           + abs.contains("Hello"));
  
        // Check if the set contains "20"
        System.out.println("Does the set"
                           + " contains '20': "
                           + abs.contains("20"));
  
        // Check if the set contains "Geeks"
        System.out.println("Does the set"
                           + " contains 'Geeks': "
                           + abs.contains("Geeks"));
    }
}

输出。

AbstractSet: [10, 20, Geeks, for]

Does the set contains 'Hello': false
Does the set contains '20': true
Does the set contains 'Geeks': true

程序 2:

// Java code to illustrate
// AbstractSet.contains()
  
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
  
        // Creating an empty set
        AbstractSet<Integer>
            abs = new TreeSet<Integer>();
  
        // Use add() method to add
        // elements in the set
        abs.add(10);
        abs.add(20);
        abs.add(30);
        abs.add(40);
        abs.add(50);
  
        // Displaying the set
        System.out.println("AbstractSet:"
                           + abs);
  
        // Check if the set contains 10
        System.out.println("\nDoes the set "
                           + "contains '10': "
                           + abs.contains(10));
  
        // Check if the set contains 50
        System.out.println("\nDoes the set"
                           + " contains '50': "
                           + abs.contains(50));
  
        // Check if the set contains 100
        System.out.println("Does the set"
                           + " contains '100': "
                           + abs.contains(100));
    }
}

输出。

AbstractSet:[10, 20, 30, 40, 50]

Does the set contains '10': true

Does the set contains '50': true
Does the set contains '100': false

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程