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


Java Set containsAll()用法及代码示例


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

用法:

public boolean containsAll(Collection C)

参数:参数C是一个Collection。此参数表示需要在此集合中检查其元素出现的集合。


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

以下示例程序旨在说明Set.containsAll()方法:

示例1:

// Java code to illustrate 
// Set containsAll() 
  
import java.util.*; 
  
class SetDemo { 
    public static void main(String args[]) 
    { 
  
        // Creating an empty set 
        Set<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("Set 1: "
                           + set); 
  
        // Creating another empty set 
        Set<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("Set 2: "
                           + set2); 
  
        // Check if the set 
        // contains same elements 
        System.out.println("\nDoes set 1 contains set 2?: "
                           + set.containsAll(set2)); 
    } 
}
输出:
Set 1: [Geeks, for, 20, 10]
Set 2: [Geeks, for, 20, 10]

Does set 1 contains set 2?: true

示例2:

// Java code to illustrate boolean containsAll() 
  
import java.util.*; 
  
class SetDemo { 
    public static void main(String args[]) 
    { 
  
        // Creating an empty set 
        Set<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("Set 1: "
                           + set); 
  
        // Creating another empty set 
        Set<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("Set 2: "
                           + set2); 
  
        // Check if the set 
        // contains same elements 
        System.out.println("\nDoes set 1 contains set 2: "
                           + set.containsAll(set2)); 
    } 
}
输出:
Set 1: [Geeks, for]
Set 2: [20, 10]

Does set 1 contains set 2: false

参考: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#containsAll(java.util.Collection)



相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 Set containsAll() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。