a shot of dev knowledge


What is the Vector.removeAll in Java?

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index and the size of a Vector can be increased or decreased. Read more about Vector here.

The removeAll method will remove all the elements of the passed collection from the Vector if present.


boolean removeAll(Collection<?> c)

This method takes the collection object to be removed from the vector as an argument.

This method returns true if the Vector object changed as a result of the call (any one of the elements from the collection is present & removed from the Vector). Otherwise, false will be returned.


import java.util.Vector;
import java.util.ArrayList;
class RemoveAll {
    public static void main( String args[] ) {
        Vector<Integer> vector = new Vector<>();
        ArrayList<Integer> list = new ArrayList<>();

        System.out.println("The vector is "+ vector);
        System.out.println("The list is "+ list);
        System.out.println("\nCalling vector.removeAll(list). Is vector changed - " + vector.removeAll(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 numbers 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 9 to 11: We create a new ArrayList object with the name list and Added two elements (1,4) to the list object using the add method.

  • In line number 15: We use the removeAll method to remove all the elements of the list from the vector. The element 1 in the list is present in the vector so it is removed. The element 4 is not present in the vector, so it is not removed. After calling the removeAll method, the content of the vector object changes, so true is returned.



View all Courses

Keep Exploring