Java HashSet containsAll()方法及示例

Java HashSet containsAll()方法及示例

Java HashSet的containsAll()方法是用来检查两个集合是否包含相同的元素。它以一个集合为参数,如果这个集合的所有元素都存在于另一个集合中,则返回True。

语法

public boolean containsAll(Collection C)

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

返回值: 如果这个集合包含了其他集合的所有元素,该方法返回True,否则返回False。

下面的程序说明了HashSet.containsAll()方法。

程序1 :

// Java code to illustrate
// HashSet containsAll()
  
import java.util.*;
  
class HashSetDemo {
    public static void main(String args[])
    {
  
        // Creating an empty set
        HashSet<String>
            set = new HashSet<String>();
  
        // Use add() method to
        // add elements in the set
        set.add("Geeks");
        set.add("for");
        set.add("Geeks");
        set.add("10");
        set.add("20");
  
        // prints the set
        System.out.println("HashSet 1: "
                           + set);
  
        // Creating another empty set
        HashSet<String>
            set2 = new HashSet<String>();
  
        // Use add() method to
        // add elements in the set
        set2.add("Geeks");
        set2.add("for");
        set2.add("Geeks");
        set2.add("10");
        set2.add("20");
  
        // prints the set
        System.out.println("HashSet 2: "
                           + set2);
  
        // Check if the set
        // contains same elements
        System.out.println("\nDoes set 1 contains set 2: "
                           + set.containsAll(set2));
    }
}

输出:

HashSet 1: [Geeks, for, 20, 10]
HashSet 2: [Geeks, for, 20, 10]

Does set 1 contains set 2: true

示例2

// Java code to illustrate boolean containsAll()
  
import java.util.*;
  
class HashSetDemo {
    public static void main(String args[])
    {
  
        // Creating an empty set
        HashSet<String>
            set = new HashSet<String>();
  
        // Use add() method to
        // add elements in the set
        set.add("Geeks");
        set.add("for");
        set.add("Geeks");
  
        // prints the set
        System.out.println("HashSet 1: "
                           + set);
  
        // Creating another empty set
        HashSet<String>
            set2 = new HashSet<String>();
  
        // Use add() method to
        // add elements in the set
        set2.add("10");
        set2.add("20");
  
        // prints the set
        System.out.println("HashSet 2: "
                           + set2);
  
        // Check if the set
        // contains same elements
        System.out.println("\nDoes set 1 contains set 2: "
                           + set.containsAll(set2));
    }
}

输出:

HashSet 1: [Geeks, for]
HashSet 2: [20, 10]

Does set 1 contains set 2: false

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程