Vector removeAll() Method in Java


The removeAll() method in Java is a part of the Vector class which is used to remove all the elements from the vector. This method returns a boolean value indicating whether the vector was modified or not.

Syntax:

public void removeAllElements()

Example:

import java.util.Vector;

public class VectorRemoveAllExample {
   public static void main(String[] args) {
      // Creating a Vector of Strings
      Vector<String> vector = new Vector<String>();

      // Adding elements to the Vector
      vector.add("Java");
      vector.add("Python");
      vector.add("C++");
      vector.add("Ruby");
      vector.add("PHP");

      // Displaying the Vector elements
      System.out.println("Vector elements before removeAll(): ");
      for (String str : vector) {
         System.out.println(str);
      }

      // Removing all the elements from the Vector
      vector.removeAllElements();

      // Displaying the Vector elements after removeAll()
      System.out.println("Vector elements after removeAll(): ");
      for (String str : vector) {
         System.out.println(str);
      }
   }
}

Output:

Vector elements before removeAll():
Java
Python
C++
Ruby
PHP
Vector elements after removeAll():

Another way to use the removeAll() method is to remove all the elements from one vector that are present in another vector. This can be done using the following syntax:

Syntax:

public boolean removeAll(Collection<?> c)

Example:

import java.util.Vector;

public class VectorRemoveAllExample {
   public static void main(String[] args) {
      // Creating two Vectors of Strings
      Vector<String> vector1 = new Vector<String>();
      Vector<String> vector2 = new Vector<String>();

      // Adding elements to the Vectors
      vector1.add("Java");
      vector1.add("Python");
      vector1.add("C++");
      vector1.add("Ruby");
      vector1.add("PHP");

      vector2.add("Java");
      vector2.add("C++");
      vector2.add("PHP");

      // Displaying the Vector elements before removeAll()
      System.out.println("Vector1 elements before removeAll(): ");
      for (String str : vector1) {
         System.out.println(str);
      }

      // Removing all the elements from vector1 that are present in vector2
      vector1.removeAll(vector2);

      // Displaying the Vector elements after removeAll()
      System.out.println("Vector1 elements after removeAll(): ");
      for (String str : vector1) {
         System.out.println(str);
      }
   }
}

Output:

Vector1 elements before removeAll():
Java
Python
C++
Ruby
PHP
Vector1 elements after removeAll():
Python
Ruby


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.