Java Vector set() Method
Vector.set()The method is a common method in JavaVectorprovided by the Vector class, used to replace the element at the specified position. This method allows you to modifyVectorthe value at a specific index in Vector, and returns the replaced old element.
Method Syntax
public E set(int index, E element)
Parameter Description
index: the index position of the element to be replaced (starting from 0)element: the new element to be stored
Return Value
- Returns the old element that was replaced.
- If the index is out of range (index < 0 || index >= size()), it will throw
IndexOutOfBoundsException
Usage Example
Basic Usage
Example
public class VectorSetExample {
public static void main(String[] args) {
// Create a Vector and add elements
Vector<String> fruits = new Vector<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println("Original Vector: " + fruits);
// Use the set() method to replace an element
String oldFruit = fruits.set(1, "Blueberry");
System.out.println("Replaced element: " + oldFruit);
System.out.println("Modified Vector: " + fruits);
}
}
Output result:
原始 Vector: [Apple, Banana, Cherry] 被替换的元素: Banana 修改后的 Vector: [Apple, Blueberry, Cherry]
Handling Exceptions
Example
public class VectorSetException {
public static void main(String[] args) {
Vector<Integer> numbers = new Vector<>();
numbers.add(10);
numbers.add(20);
try {
// Attempt to set a non-existent index
numbers.set(3, 30);
} catch (IndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output result:
错误: Index: 3, Size: 2
Method Characteristics
Thread Safety
VectorAs a thread-safe collection class, thereforeset()The method is also thread-safe and can be used in multithreaded environments without additional synchronization.
Time Complexity
set()The method's time complexity is O(1), because it can directly access elements by index.
Comparison with ArrayList's set()
| Feature | Vector.set() | ArrayList.set() |
|---|---|---|
| Thread Safety | Yes | no |
| Performance | Slightly slower (due to synchronization overhead) | Faster |
| Exception Handling | Same | Same |
Practical Application Scenarios
Batch Updating Data
Example
// Assume temperatures has already been filled with data
// Batch update temperature values (e.g., increase by 1 degree)
for (int i = 0; i < temperatures.size(); i++) {
temperatures.set(i, temperatures.get(i) + 1.0);
}
State Updates in Game Development
Example
// Initialize game characters
// Update a character's state
gameCharacters.set(characterIndex, updatedCharacter);
Data Modification in Multithreaded Environments
Example
Vector<String> sharedData = new Vector<>();
// Thread 1
new Thread(() -> {
sharedData.set(0, "Thread1 update");
}).start();
// Thread 2
new Thread(() -> {
sharedData.set(1, "Thread2 update");
}).start();
Notes
Index Range Check
Before using theset()method, it's best to check whether the index is valid:
Example
vector.set(index, newElement);
} else {
// Handle the case of an invalid index
}
Null Value Handling
VectorAllows storingnullvalues, thereforeset()the method can also be used to setnull:
Example
Performance Considerations
When thread safety is not required, consider usingArrayListinsteadVector, becauseArrayListofset()the set() method has no synchronization overhead and has better performance.
Summary
Vector.set()The method is an effective way to modifyVectorelements in the Vector collection. It has the following characteristics:
- You can directly replace elements by index
- Returns the old element that was replaced
- It is a thread-safe operation
- High operational efficiency (O(1) time complexity)
When using it, pay attention to the index range to avoidIndexOutOfBoundsException. Depending on the application scenario, choose whether to useVector(if thread safety is needed) orArrayList(for higher performance).
Java Vector