Java Vector retainAll() Method Tutorial

In this section, we will learn what the Vector retainAll() method is and how to use it in Java.

What is Java Vector retainAll() Method?

The Java Vector retainAll() method is used to compare the elements of a vector object with the elements of a collection and remove any element that is not in the target collection as well.

Java Vector retainAll() Method Syntax:

public boolean retainAll(Collection<?> c)

retainAll() Method Parameters:

The method takes one argument and that is a reference to a collection object that we want to compare its elements with the elements of the vector object that this method is called with.

retainAll() Method Return Value:

The return value of this method is of Boolean type.

The method returns true if one or more elements of a vector object was removed as a result of calling this method. Otherwise, the value false will return instead.

retainAll() Method Exceptions:

ClassCastException: We get this exception if the elements of the target collection are of incompatible datatype compared to the datatype of the elements in the vector object.

NullPointerException: we get this exception of we set the value null as the argument of this method.

Example: using Vector retainAll() method

import java.util.Vector; 
import java.util.ArrayList;
public class Main {

    public static void main(String[] args){
        
      Vector <Integer> vector = new Vector<>();
      vector.addElement(1);
      vector.addElement(2);
      vector.addElement(3);
      vector.addElement(4);
      vector.addElement(5);
      
      ArrayList<Integer> array = new ArrayList<>();
      array.add(2);
      array.add(5);

      vector.retainAll(array);

      for(int i : vector){
         System.out.println(i);
      }
    }
}

Output:

2

5
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies