Collections

ArrayList containsAll Example in Java Code

Table of Contents

Program

import java.util.ArrayList;

public class ArraylistContainsAll
{
           public static void main(String[] args)
	   {
	      ArrayList<String> A1 = new ArrayList<String>();
	      A1.add("red");
	      A1.add("green");
	      A1.add("blue");
	      System.out.println("ArrayList 1: " + A1);
	      ArrayList<String> B1 = new ArrayList<String>();
	      B1.add("blue");
	      B1.add("green");
	      System.out.println("ArrayList 2: " + B1);
	      boolean output1 = A1.containsAll(B1);
	      System.out.println("Does ArrayList 1 contains all elements of ArrayList 2?: " + output1);
	      boolean output2 = A1.containsAll(A1);
	      System.out.println("Does ArrayList 2 contains all elements of ArrayList 1?: " + output2);
	      boolean result = A1.contains("God");
	      System.out.println("Is God present in the List: " + result);
	}
}      

Output

ArrayList 1: [red, green, blue]
ArrayList 2: [blue, green]
Does ArrayList 1 contains all elements of ArrayList 2?: true
Does ArrayList 2 contains all elements of ArrayList 1?: true
Is God present in the List: false

Description

public boolean containsAll​(Collection c)

Returns true if this collection contains all of the elements in the specified collection.

Specified by:

containsAll in interface Collection<E>

Implementation Requirements:

This implementation iterates over the specified collection, checking each element returned by the iterator in turn to see if it’s contained in this collection. If all elements are so contained true is returned, otherwise false.

Parameters:

c – collection to be checked for containment in this collection

Returns:

true if this collection contains all of the elements in the specified collection

Throws:

ClassCastException – if the types of one or more elements in the specified collection are incompatible with this collection (optional)
NullPointerException – if the specified collection contains one or more null elements and this collection does not permit null elements (optional), or if the specified collection is null.