📌  相关文章
📜  用示例列出Java中的 containsAll() 方法

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

用示例列出Java中的 containsAll() 方法

Java中 List 接口的 containsAll() 方法用于检查该 List 是否包含指定 Collection 中的所有元素。所以基本上它用于检查 List 是否包含一组元素。

句法:

boolean containsAll(Collection col)

参数:此方法接受一个强制参数col ,该参数属于集合类型。这是需要检查其元素是否存在于列表中的集合。

返回值:如果集合col中的所有元素都存在于 List 中,则该方法返回True ,否则返回False

异常:如果指定的集合为 NULL,则该方法抛出NullPointerException

下面的程序说明了 containsAll() 方法:

方案一:

// Java code to illustrate containsAll() method
import java.util.*;
  
public class ListDemo {
    public static void main(String args[])
    {
        // Creating an empty list
        List list = new ArrayList();
  
        // Use add() method to add elements
        // into the List
        list.add("Welcome");
        list.add("To");
        list.add("Geeks");
        list.add("4");
        list.add("Geeks");
  
        // Displaying the List
        System.out.println("List: " + list);
  
        // Creating another empty List
        List listTemp = new ArrayList();
  
        listTemp.add("Geeks");
        listTemp.add("4");
        listTemp.add("Geeks");
  
        System.out.println("Are all the contents equal? "
                           + list.containsAll(listTemp));
    }
}
输出:
List: [Welcome, To, Geeks, 4, Geeks]
Are all the contents equal? true

方案二:

// Java code to illustrate containsAll() method
import java.util.*;
  
public class ListDemo {
    public static void main(String args[])
    {
        // Creating an empty list
        List list = new ArrayList();
  
        // Use add() method to add elements
        // into the List
        list.add(10);
        list.add(15);
        list.add(30);
        list.add(20);
        list.add(5);
  
        // Displaying the List
        System.out.println("List: " + list);
  
        // Creating another empty List
        List listTemp = new ArrayList();
  
        listTemp.add(30);
        listTemp.add(15);
        listTemp.add(5);
  
        System.out.println("Are all the contents equal? "
                           + list.containsAll(listTemp));
    }
}
输出:
List: [10, 15, 30, 20, 5]
Are all the contents equal? true

参考:https: Java Java.util.Collection)