Java ArrayList containsAll()

The syntax of the containsAll() method is:

arraylist.containsAll(Collection c);

Here, arraylist is an object of the ArrayList class.


containsAll() Parameters

The containsAll() method takes a single parameter.

  • collection - checks if all elements of collection are present in the arraylist.

containsAll() Return Value

  • returns true if the arraylist contains all elements of collection
  • throws ClassCastException if the class of elements present in arraylist is incompatible with the class of elements in the specified collection
  • throws NullPointerException if collection contains null elements and the arraylist does not allow null values

Note: We can say that the containsAll() method checks if the collection is a subset of the arraylist.


Example 1: Java ArrayList containsAll()

Output

ArrayList 1: [JavaScript, Python, Java]
ArrayList 2: [Java, Python]
ArrayList 1 contains all elements of ArrayList 2: true
ArrayList 2 contains all elements of ArrayList 1: false

In the above example, we have created two arraylists named languages1 and languages2. Notice the expression,

// return true
languages1.containsAll(languages2)

Here, the containsAll() method checks if languages1 contains all elements of languages2. Hence, the method returns true. However, notice the following expression,

// return false
languages2.containsAll(languages1)

Here, the containsAll() method checks if languages2 contains all elements of languages1. Hence, it returns false.

Note: The containsAll() method is not specific to the ArrayList class. The class inherits from the List interface.


Example 2: containsAll() Between Java ArrayList and HashSet

Output

ArrayList: [1, 2, 3]
HashSet: [2, 3]
ArrayList contains all elements of HashSet: true
HashSet contains all elements of ArrayList: false

In the above example, we have created an arraylist named numbers and a hashset named primeNumbers. Notice the expressions,

// check if ArrayList contains HashSet
// return true
numbers.containsAll(primeNumbers)

// check if HashSet contains ArrayList
// return false
primeNumbers.containsAll(numbers)

Note: We can get the common elements between ArrayList and HashSet using the Java ArrayList retainAll() method.