Java Vector retainAll(Collection c) Method Example

The removeAll(Collection<?> c) method of java.util.Vector class will remove all the content of the Vector, whereas retainAll(Collection<?> c) method will retain only the elements in the Vector that are contained in the specified Collection.

Signature

public boolean retainAll(Collection<?> c)

This method will retain only the elements in the Vector that are contained in the specified Collection. Throws java.lang.ClassCastException if the types of one or more elements in this vector are incompatible with the specified collection and java.lang.NullPointerException if the vector contains one or more null elements and the specified collection does not support null elements

Example

The following example shows the usage of java.util.Vector.retainAll(c) method.

import java.util.Vector;

public class RetailAllMethodVectorExample 
{
    public static void main(String args[])
    {
     // create an empty Vector
        Vector vector1 = new Vector();
        
        // use add() method to add elements to the Vector
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        vector1.add("Element4");
        vector1.add("Element5");
        vector1.add("Element6");
        vector1.add("Element7");
        vector1.add("Element8");
        
        //Printing the elements of the Vector
        System.out.println("**Elements of the Vector1 before retainAll**");
        for(String temp:vector1)
        {
            System.out.println(temp);
        }
        //create a retain vector
        Vector retainVector = new Vector();
        
        // use add() method to add elements to the Vector
        retainVector.add("Element2");
        retainVector.add("Element3");
        retainVector.add("Element4");
        retainVector.add("Element5");
        
        //Check retainAll
        vector1.retainAll(retainVector);
        
        //Printing the elements of the Vector
        System.out.println("**Elements of the Vector1 After retainAll**");
        for(String temp:vector1)
        {
            System.out.println(temp);
        }
    }
}

Output

**Elements of the Vector before retainAll**
Element1
Element2
Element3
Element4
Element5
Element6
Element7
Element8
**Elements of the Vector After retainAll**
Element2
Element3
Element4
Element5

Leave a Reply

Your email address will not be published. Required fields are marked *