📌  相关文章
📜  Java中的 AbstractSet containsAll() 方法及示例

📅  最后修改于: 2022-05-13 01:55:19.873000             🧑  作者: Mango

Java中的 AbstractSet containsAll() 方法及示例

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

句法:

public boolean containsAll(Collection C)

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

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

下面的程序说明了 AbstractSet.conatinsAll() 方法:

方案一:

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

Does set 1 contains set 2: true

方案二:

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

Does set 1 contains set 2: false