What is the Vector.containsAll method in Java?
The containsAll method checks if all the elements of the specific collection object are present in the Vector object.
The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index and the size of aVectorcan be increased or decreased. Read more aboutVectorhere.
Syntax
public boolean containsAll(Collection<?> c)
This method takes the collection to be checked if it is present in the vector object.
It will return true if all the elements of the passed collection are present in the Vector object.
Working example
Please click the “Run” button below to see how the
containsAllmethod works.
import java.util.Vector;import java.util.ArrayList;class containsAll {public static void main( String args[] ) {Vector<Integer> vector = new Vector<>();vector.add(1);vector.add(2);vector.add(3);ArrayList<Integer> list1 = new ArrayList<>();list1.add(1);list1.add(3);System.out.println("The vector is "+ vector);System.out.println("\nlist1 is "+ list1);System.out.println("If vector contains all elements of list1 : "+ vector.containsAll(list1));ArrayList<Integer> list2 = new ArrayList<>();list2.add(4);System.out.println("\nlist2 is "+ list2);System.out.println("If vector contains all elements of list2 : "+ vector.containsAll(list2));}}
Explanation
In the above code:
-
Line 1 and 2: We imported the
VectorandArrayListclass -
Line 5: We created an object for the
Vectorclass with the namevector. -
Lines 6 - 8: We added three elements (
1,2,3) to the above created vector object. -
Line 10: We created a new
ArrayListobject with the namelist1. -
Line 11 and 12: We added the elements
1,3tolist1. -
Line 16: We used the
containsAllmethod to check if all the elements oflist1are present in thevector. In this case,trueis returned. This is because all the elements (1,3) oflist1are present in thevector. -
Line 18: We created a new
ArrayListobject with the namelist2. -
Line 19: We added an element
4tolist2. -
Line 22: We used the
conainsAllmethod to check if all the elements of thelist2are present in thevector. In this case,falseis returned. This is because element4of thelist2is not present in thevector.