YouTip LogoYouTip

Java Vector Retainall

## Java Vector retainAll() Method In Java, the `Vector` class provides the `retainAll()` method to perform bulk intersection operations on collections. This method modifies the target vector so that it retains only the elements that are also contained in the specified collection. In other words, it removes all elements from the vector that do not exist in the passed collection. --- ### Syntax The method signature for `retainAll()` is defined as follows: ```java public boolean retainAll(Collection c) ``` ### Parameters * **`Collection c`**: The collection containing the elements to be retained in the vector. This can be any object that implements the `Collection` interface, such as an `ArrayList`, `HashSet`, `LinkedList`, or another `Vector`. ### Return Value The method returns a `boolean` value: * **`true`**: If the vector was modified as a result of the call (i.e., at least one element was removed). * **`false`**: If the vector did not change (i.e., all elements in the vector were already present in the specified collection). ### How It Works Under the Hood When you invoke the `retainAll()` method, the following steps occur: 1. The method iterates through each element of the current vector. 2. For each element, it checks whether the element exists in the specified collection `c` (typically using the `c.contains(element)` check). 3. If the element is **not** present in collection `c`, it is removed from the vector. 4. Once the operation is complete, the vector contains only the intersection of its original elements and the elements in collection `c`. --- ## Code Example The following example demonstrates how to use the `retainAll()` method to find the intersection of a `Vector` and a `List`. ```java import java.util.Vector; import java.util.Arrays; import java.util.List; public class VectorRetainAllExample { public static void main(String[] args) { // Create the initial Vector Vector vector1 = new Vector<>(Arrays.asList("Apple", "Banana", "Orange", "Grape")); // Create the collection of elements to retain (using a List) List list = Arrays.asList("Banana", "Grape", "Mango"); System.out.println("Original Vector: " + vector1); System.out.println("Collection of elements to retain: " + list); // Call the retainAll() method boolean changed = vector1.retainAll(list); System.out.println("Method returned: " + changed); System.out.println("Vector after retainAll(): " + vector1); } } ``` ### Output ```text Original Vector: [Apple, Banana, Orange, Grape] Collection of elements to retain: [Banana, Grape, Mango] Method returned: true Vector after retainAll(): [Banana, Grape] ``` --- ## Important Considerations 1. **Element Comparison (`equals` and `hashCode`)**: The `retainAll()` method relies on the `equals()` method of the elements to determine equality. If you are storing custom objects in your vector, ensure you have properly overridden the `equals()` and `hashCode()` methods in your custom class. 2. **Null Pointer Exception**: If the specified collection parameter `c` is `null`, the method will throw a `NullPointerException`. 3. **Concurrent Modification**: If the vector is structurally modified while the `retainAll()` operation is in progress (except by the thread executing the operation), the behavior is undefined and may throw a `ConcurrentModificationException`. 4. **Performance Implications**: For large collections, this operation can be relatively slow. If the passed collection `c` is a `List`, the lookup complexity for `contains()` is $O(N)$, making the overall complexity $O(M \times N)$ where $M$ is the size of the vector and $N$ is the size of the collection. Passing a `HashSet` instead of a `List` can significantly improve performance to $O(M)$ because set lookups are $O(1)$ on average. --- ## Practical Use Cases * **Data Filtering**: Easily filter out elements from a dataset that do not match a predefined whitelist. * **Set Intersection**: Calculate the common elements (intersection) between two collections. * **Permission Control**: Filter a user's assigned permissions against a list of currently active system permissions to keep only the valid ones. --- ## Comparison with Related Methods The table below highlights the differences between `retainAll()` and other common bulk collection operations in Java: | Method | Description | Modifies Current Collection? | Return Value Meaning | | :--- | :--- | :--- | :--- | | **`retainAll(Collection c)`** | Retains only elements that are also in `c` (Intersection). | **Yes** | `true` if any elements were removed. | | **`removeAll(Collection c)`** | Removes all elements that are also in `c` (Difference). | **Yes** | `true` if any elements were removed. | | **`containsAll(Collection c)`** | Checks if the collection contains all elements of `c`. | **No** | `true` if all elements of `c` are present. | | **`addAll(Collection c)`** | Appends all elements of `c` to the end of the collection (Union). | **Yes** | `true` if the collection changed. | --- ## Summary The `Vector.retainAll()` method is a powerful utility for performing intersection operations directly on a vector. By understanding its mechanics, performance characteristics, and requirements for object equality, you can write cleaner and more efficient collection-processing code in Java.
← Java Vector SizeJava Vector Set β†’