Java Vector ensureCapacity() Method
ensureCapacity()is aVectormethod provided by the Vector class, used to ensureVectorcan hold the specified number of elements without reallocating the internal array space. This method can help us optimizeVectorperformance, especially when we know in advance that a large number of elements need to be stored.
Method Syntax
public void ensureCapacity(int minCapacity)
Parameter Description
minCapacity: the minimum capacity value you want to ensure
Return Value
This method has no return value (void type).
Method Function
ensureCapacity()The main function of this method is:
- If the current
Vectorcapacity of the Vector is less than the specified minimum capacity, increase its capacity - If the current capacity is already large enough, it does nothing.
- By preallocating enough space, the number of expansions when adding elements later can be reduced.
Usage Example
Basic Usage
Example
public class VectorExample {
public static void main(String[] args) {
// Create a Vector with an initial capacity of 5
Vector<String> vector = new Vector<>(5);
System.out.println("Initial capacity: " + vector.capacity());
// Ensure the capacity is at least 10
vector.ensureCapacity(10);
System.out.println("Capacity after calling ensureCapacity(10): " + vector.capacity());
}
}
Output result
初始容量: 5 调用ensureCapacity(10)后的容量: 10
Practical Application Scenarios
Example
public class BulkDataProcessing {
public static void main(String[] args) {
// Suppose we know we need to process about 1000 pieces of data
Vector<Integer> data = new Vector<>();
// Preallocate enough space
data.ensureCapacity(1000);
// Add a large amount of data
for (int i = 0; i < 1000; i++) {
data.add(i);
}
System.out.println("Final capacity: " + data.capacity());
System.out.println("Number of elements: " + data.size());
}
}
Output result
最终容量: 1000 元素数量: 1000
How It Works
VectorInternally, it uses an array to store elements. When a new element is added, if the current array is full,Vectorit automatically creates a larger array and copies all elements to the new array. This process is called "expansion".
ensureCapacity()The method works as follows:
- Check whether the current capacity is less than the minimum capacity specified by the parameter
- If so, create a new larger array
- Copy the existing elements to the new array
- Update the internal reference to point to the new array
Performance Considerations
Why use ensureCapacity()
- Reduce the number of expansions: Frequent expansion can affect performance, especially when processing large amounts of data
- Memory optimization: Preallocating enough space can avoid multiple small-scale expansions
- Performance improvement: Reduces array copy operations and improves overall efficiency
Expansion Strategy
If you do not useensureCapacity(),Vectorit has its own expansion strategy:
- By default,
Vectorthe initial capacity is 10 - When expansion is needed, the capacity doubles by default (that is, new capacity = old capacity * 2)
- You can also specify a different growth amount.
Notes
ensureCapacity()It only increases capacity and never decreases it.- If the specified minimum capacity is less than the current capacity, the method does nothing.
- This method does not change
Vectorthe Vector's size(); it only affects capacity(). - Over-allocating capacity may waste memory space.
Comparison with ArrayList
AlthoughArrayListalso hasensureCapacity()the method, there are some differences in implementation between the two:
| Feature | Vector | ArrayList |
|---|---|---|
| Thread safety | Yes (synchronized method) | no |
| Default expansion strategy | Capacity doubles | Capacity increases by 50% |
| Performance | Slightly slower (because of synchronization) | Faster |
Summary
VectorofensureCapacity()This method is a useful tool that can help us optimize the performance of collections, especially when processing large amounts of data. By preallocating enough space, frequent expansion operations can be avoided, thereby improving the overall efficiency of the program.
Remember, when using this method, you should set the minimum capacity value reasonably according to actual needs. It should be neither too small (causing frequent expansion) nor too large (causing memory waste).
Other Extensions
Java Vector