Java Vector remove() Method
VectorThe class is an important part of the Java collection framework. It implements a growable array of objects.remove()The method isVectorone of the core methods provided by the class, used to remove a specified element from the vector.
VectorThe class provides multiple overloadedremove()methods, allowing developers to remove elements in different ways:
- Remove an element by index position
- Remove an element by object reference
- Remove all elements
Method Syntax
VectorThe class provides the following threeremove()methods:
public E remove(int index)
// 2. Remove the first occurrence of the specified element
public boolean remove(Object o)
// 3. Remove all elements
public void clear() // Actually a method inherited from AbstractCollection
Method Details
1. remove(int index)
Function: Removes the element at the specified position in the vector and shifts all subsequent elements to the left (i.e., their indices decrease by 1).
Parameter:
index- The index position of the element to be removed (starting from 0)
Return Value:
- Returns the removed element
Exception:
- If the index is out of range (index < 0 || index >= size()), it throws
ArrayIndexOutOfBoundsException
Example Code:
Example
public class VectorRemoveExample {
public static void main(String[] args) {
Vector<String> fruits = new Vector<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println("Original vector: " + fruits);
// Remove the element at index 1 (Banana)
String removed = fruits.remove(1);
System.out.println("Removed element: " + removed);
System.out.println("Vector after removal: " + fruits);
}
}
Output:
原始向量: [Apple, Banana, Cherry] 被移除的元素: Banana 移除后的向量: [Apple, Cherry]
2. remove(Object o)
Function: Removes the first occurrence of the specified element from the vector (if it exists).
Parameter:
o- The element to be removed from the vector
Return Value:
- If the vector contains the specified element, returns
true - Otherwise returns
false
Example Code:
Example
public class VectorRemoveObjectExample {
public static void main(String[] args) {
Vector<Integer> numbers = new Vector<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(20); // Duplicate elements
System.out.println("Original vector: " + numbers);
// Remove the first occurrence of 20
boolean result = numbers.remove(Integer.valueOf(20));
System.out.println("Removal result: " + result);
System.out.println("Vector after removal: " + numbers);
}
}
Output:
原始向量: [10, 20, 30, 20] 移除操作结果: true 移除后的向量: [10, 30, 20]
3. clear()
Function: Removes all elements from the vector, making it an empty vector.
Example Code:
Example
public class VectorClearExample {
public static void main(String[] args) {
Vector<Double> prices = new Vector<>();
prices.add(19.99);
prices.add(29.99);
prices.add(39.99);
System.out.println("Original vector: " + prices);
// Clear the vector
prices.clear();
System.out.println("Vector after clearing: " + prices);
System.out.println("Vector size: " + prices.size());
}
}
Output:
原始向量: [19.99, 29.99, 39.99] 清空后的向量: [] 向量大小: 0
Method Comparison
| Method | Parameter Type | Return Value | Exception | Purpose |
|---|---|---|---|---|
| remove(int index) | int | E (the removed element) | ArrayIndexOutOfBoundsException | Remove the element at a specific position by index |
| remove(Object o) | Object | boolean | None | Remove the first matching element by value |
| clear() | None | void | None | Remove all elements |
Usage Notes
Thread Safety:
VectorIt is thread-safe, and all its methods use synchronization mechanisms. However, in single-threaded environments, this may bring unnecessary performance overhead.Performance Considerations:
remove(int index)The time complexity of the method is O(n) because it needs to shift subsequent elements. Frequent removal operations may affect performance.Null Value Handling:
VectorAllows storingnullvalues, you can useremove(null)to removenullelements.Element Comparison:
remove(Object o)The method usesequals()method to determine whether elements match, so make sure the element'sequals()method is correctly implemented.Alternatives: After Java 1.2,
ArrayListis usually used asVectora non-synchronized alternative to, unless thread safety is truly needed.
Best Practices
Batch Removal: If you need to remove multiple elements, consider using
removeAll(Collection c)method.Removal During Iteration: When traversing
Vectorand removing elements, you should useIteratorofremove()method to avoidConcurrentModificationException。Capacity Adjustment: After frequent removal operations, you can use
trimToSize()method to reduce the vector's capacity and save memory.Checking Existence: Before removing an element, you can use
contains(Object o)method to check whether the element exists.
FAQ
Q1: What is the difference between remove(int index) and remove(Object o)?
remove(int index)removes the element by index position, whileremove(Object o)removes the first matching element by element value. WhenVectorcontains integers, Java will automatically select the matching method, so special attention is needed:
Example
vec.add(1);
vec.add(2);
vec.remove(1); // Remove the element at index 1 (value 2)
vec.remove(Integer.valueOf(1)); // Remove the element with value 1
Q2: How to safely remove elements during iteration?
UseIteratorfor iteration and removal:
Example
// Add elements...
Iterator<String> it = vec.iterator();
while (it.hasNext()) {
String s = it.next();
if (s.equals("Element to remove")) {
it.remove(); // Safe removal
}
}
Q3: Does the remove() method affect the capacity of Vector?
No.remove()The method only reduces theVectorsize, but does not automatically reduce its capacity. If you need to shrink the capacity, you can calltrimToSize()method.
Summary
Vectorofremove()The method provides a flexible way to remove elements. Understanding the usage scenarios and precautions of its different overloaded forms is very important for writing robust Java programs. In most modern Java applications, unless thread safety is needed,ArrayListmay be a better choice, but understandingVectorand its methods is still valuable.
Java Vector