Java Vector removeAll() Method

Java Vector Java Vector


removeAll()The method is in JavaVectora common method provided by the class, used to remove from the currentVectorremove all elements contained in the specified collection. This method inherits fromAbstractCollectionclass, and inVectoris implemented in the class.

Method Syntax

public boolean removeAll(Collection<?> c)

Parameters

  • c: Contains elements to be removed from thisVectorcollection of elements to be removed

Return Value

  • IfVectorchanges because of calling this method, returnstrue
  • IfVectorhas not changed (i.e., no elements in the specified collection exist inVector), then returnsfalse

Detailed Explanation of the Method Functionality

removeAll()The main function of the method is to remove fromVectorbatch remove elements. It checksVectoreach element in, if the element exists in the parametercspecified collection, then removes it fromVectorremove it.

Important Features

  1. Batch operation: Can remove multiple elements at once
  2. Collection-based removal: The removal criterion is based on the contents of another collection
  3. **Modifies the originalVector**: This method directly modifies theVectorobject
  4. Preserve order: After removing elements, the order of remaining elements stays unchanged

Usage Examples

Example 1: Basic Usage

Example

import java.util.Vector;
import java.util.Arrays;

public class VectorRemoveAllExample {
    public static void main(String[] args) {
        // Create a Vector
        Vector<String> vector = new Vector<>();
        vector.add("Apple");
        vector.add("Banana");
        vector.add("Orange");
        vector.add("Grape");
        vector.add("Mango");
       
        // Create a collection of elements to remove
        Vector<String> toRemove = new Vector<>(Arrays.asList("Banana", "Grape"));
       
        // Use the removeAll() method
        boolean changed = vector.removeAll(toRemove);
       
        System.out.println("Vector has been modified: " + changed);
        System.out.println("Modified Vector: " + vector);
    }
}

Output result:

Vector 是否被修改: true
修改后的 Vector: [Apple, Orange, Mango]

Example 2: Removing All Elements

Example

import java.util.Vector;
import java.util.Arrays;

public class RemoveAllElements {
    public static void main(String[] args) {
        Vector<Integer> numbers = new Vector<>(Arrays.asList(1, 2, 3, 4, 5));
       
        // Create a collection containing all elements
        Vector<Integer> allElements = new Vector<>(numbers);
       
        // Remove all elements
        numbers.removeAll(allElements);
       
        System.out.println("Vector after clearing: " + numbers);
    }
}

Output result:

清空后的 Vector: []

Notes

  1. Empty collection handling: If the parametercis an empty collection, the method does not throw an exception, but returnsfalse

    Example

    Vector<String> v = new Vector<>(Arrays.asList("A", "B", "C"));
    boolean result = v.removeAll(new ArrayList<String>());
    System.out.println(result);  // Outputs false
  2. nullValue handling:

    • If the parametercisnull, it will throwNullPointerException
    • IfVectorcontainsnullelement, and the collectioncalso containsnull, thennullwill be removed
  3. Performance considerations: For largeVector, the performance of this method may not be high, because its time complexity is O(n*m), where n isVectorthe size of, m is the collectioncthe size of


Comparison with Related Methods

Method Function description Parameter Return value
removeAll(Collection) Removes all elements contained in the specified collection Collection boolean
retainAll(Collection) Retains all elements contained in the specified collection, removes others Collection boolean
clear() Removes all elements None void
remove(Object) Removes a single specified element Object boolean
remove(int) Removes the element at the specified index Index The removed element

Practical Application Scenarios

  1. Data filtering: Remove elements that do not meet conditions from a data collection
  2. Blacklist handling: Remove blacklisted users from the user list
  3. Data cleaning: Remove invalid or test data from the dataset
  4. Set operations: Implement the difference operation of sets

Application Example: Filtering Invalid Data

Example

import java.util.Vector;
import java.util.Arrays;

public class DataFilter {
    public static void main(String[] args) {
        Vector<String> rawData = new Vector<>(Arrays.asList(
            "valid1", "invalid", "valid2", "error", "valid3", "corrupted"));
           
        Vector<String> invalidPatterns = new Vector<>(Arrays.asList(
            "invalid", "error", "corrupted"));
           
        // Remove all invalid data
        rawData.removeAll(invalidPatterns);
       
        System.out.println("Filtered data: " + rawData);
    }
}

Output result:

过滤后的数据: [valid1, valid2, valid3]

Summary

Vector.removeAll()is a practical batch removal method, which makes it simple and efficient to remove multiple elements from a collection. Understanding and correctly using this method can help you write cleaner and more efficient Java code. Remembering its behavioral characteristics and precautions can avoid common errors and performance issues.

Java Vector Java Vector

Other Extensions