Java Vector Trimtosize
[ Java Vector](#)
* * *
`trimToSize()` is a utility method provided by the `Vector` class in Java, used to optimize the memory usage of `Vector`. This method adjusts the capacity of the `Vector` to the actual number of elements currently stored (size), thereby reducing unnecessary memory footprint.
### Method Syntax
public void trimToSize()
### Class
`java.util.Vector`
* * *
## Method Description
The `Vector` class uses an internal array to store elements. When elements are added to a `Vector`, if the current array is full, `Vector` automatically expands its capacity (typically by 1.5x or 2x). While this mechanism improves efficiency when adding elements, it can also lead to memory waste.
The purpose of the `trimToSize()` method is to adjust the internal array size of the `Vector` to exactly fit all current elements, releasing excess memory space.
### Use Cases
* After adding many elements to a `Vector` and then deleting some, resulting in capacity far exceeding the actual element count
* In memory-sensitive applications where memory optimization is needed
* When the `Vector` content is no longer expected to change and memory savings are desired
* * *
## Implementation Principle
### Source Code Analysis
Below is the implementation of the `trimToSize()` method in the `Vector` class:
## Example
public synchronized void trimToSize(){
modCount++;
int oldCapacity = elementData.length;
if(elementCount < oldCapacity){
elementData =Arrays.copyOf(elementData, elementCount);
}
}
### Implementation Steps
1. Increment the modification counter `modCount` (used for fast-fail mechanism)
2. Get the current internal array capacity `oldCapacity`
3. If the current element count `elementCount` is less than the array capacity:
* Use `Arrays.copyOf()` to create a new array with size `elementCount`
* Copy the original array contents to the new array
* Point the `elementData` reference to the new array
### Notes
* This method is synchronized (`synchronized`), thread-safe
* After calling this method, if new elements are added, `Vector` will still automatically expand
* For large `Vector` objects, this operation may incur some performance overhead
* * *
## Usage Examples
### Basic Usage
## Example
import java.util.Vector;
public class VectorTrimToSizeExample {
public static void main(String[] args){
// Create a Vector with initial capacity of 10
Vector vector =new Vector(10);
// Add 5 elements
for(int i =0; i <5; i++){
vector.add("Item "+(i +1));
}
System.out.println("Size: "+ vector.size());// Output: 5
System.out.println("Capacity: "+ vector.capacity());// Output: 10
// Call trimToSize()
vector.trimToSize();
System.out.println("Capacity after trim: "+ vector.capacity());// Output: 5
}
}
### Practical Application Scenarios
## Example
import java.util.Vector;
public class VectorMemoryOptimization {
public static void main(String[] args){
// Simulate a scenario processing large amounts of data
Vector data =new Vector(10000);
// Add a large amount of data
for(int i =0; i <8000; i++){
data.add(i);
}
// After processing data, delete half
for(int i =0; i <4000; i++){
data.remove(0);
}
System.out.println("Before trim - Size: "+ data.size()+
", Capacity: "+ data.capacity());
// Output: Before trim - Size: 4000, Capacity: 10000
// Optimize memory usage
data.trimToSize();
System.out.println("After trim - Size: "+ data.size()+
", Capacity: "+ data.capacity());
// Output: After trim - Size: 4000, Capacity: 4000
}
}
* * *
## Performance Considerations
### Time Complexity
The time complexity of the `trimToSize()` method is O(n), where n is the number of elements in the `Vector`. This is because it needs to copy the original array to a new array.
### Space Complexity
This method creates a new array, so it will temporarily use additional memory space, but ultimately will release the excess memory.
### Usage Suggestions
* Do not call `trimToSize()` frequently, especially within loops
* Call it when the `Vector` content is essentially no longer changing
* For small `Vector` objects, the optimization effect is not significant and can be ignored
* * *
## Comparison with Other Methods
### Comparison with ArrayList's trimToSize()
`ArrayList` also has a `trimToSize()` method with a similar implementation principle, but `ArrayList`'s method is not synchronized.
### Comparison with ensureCapacity()
| Method | Purpose | Parameters | Thread-Safe |
| --- | --- | --- | --- |
| `trimToSize()` | Shrink capacity to current size | None | Yes |
| `ensureCapacity(int minCapacity)` | Ensure minimum capacity | Minimum capacity value | Yes |
* * *
## Summary
`Vector.trimToSize()` is a useful memory optimization method, especially suitable for the following scenarios:
1. After a `Vector` has undergone many add and remove operations
2. In environments with limited memory resources
3. When the `Vector` content is confirmed to no longer change
Notes when using:
* This method creates a new array and copies elements, which has some performance overhead
* After calling, if elements are added, `Vector` will still automatically expand
* For small `Vector` objects or frequently changing `Vector` objects, it may not be necessary to use
Reasonably using `trimToSize()` can help optimize the memory usage efficiency of Java programs.
[ Java Vector](#)
YouTip