What is the Vector.retainAll method in Java?
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.
The retainAll method removes all the elements of the Vector object which are not present in the passed collection.
Syntax
boolean retainAll(Collection<?> c)
Parameters
This method takes the collection object to be retained in this Vector object as an argument.
Return value
This method returns true if the Vector changes as a result of the call (any element is removed from the Vector due to the element not being present in the collection). Otherwise, false is returned.
Code
import java.util.Vector;import java.util.ArrayList;class RetainAll {public static void main( String args[] ) {Vector<Integer> vector = new Vector<>();vector.add(1);vector.add(2);vector.add(3);ArrayList<Integer> list = new ArrayList<>();list.add(1);list.add(4);System.out.println("The vector is "+ vector);System.out.println("The list is "+ list);System.out.println("\nCalling vector.retainAll(list). Is vector changed - " + vector.retainAll(list));System.out.println("\nThe vector is "+ vector);}}
In the code above,
In line numbers 1 and 2: We import the Vector and ArrayList classes.
From line number 5 to 8: We create a new Vector object with the name vector and add three elements (1,2,3) to the vector object using the add method.
From line numbers 10 to 12: We create a new ArrayList object with the name list and add two elements (1,4) to the list object using the add method.
In line number 16: We use the retainAll method to retain only elements which are present in the list. In our case, the elements of the list and vector are listed below:
Elements of list -- 1,4
Elements of vector -- 1,2,3
The retainAll will,
-
Check if element
1ofvectoris present in thelist. Thelistcontains1. So the1is retained in thevector. -
Check if element
2ofvectoris present in thelist. Thelistdoesn’t contain2. So the2is removed from thevector. -
Check if element
3ofvectoris present in thelist. Thelistdoesn’t contain3. So the3is removed from thevector.
The resulting vector will be [1].