Java Vector trimToSize() Method

Java Vector Java Vector


trimToSize()is, in Java,Vectora utility method provided by the class, used to optimizeVectorthe memory usage of. This method willVectoradjust the capacity (capacity) to the current actual number of stored elements (size), thereby reducing unnecessary memory usage.

Method Syntax

public void trimToSize()

Containing Class

java.util.Vector


Method Purpose

VectorThe class internally uses an array to store elements. WhenVectoradding elements, if the current array is full,Vectorit will automatically expand (usually to 1.5 or 2 times the current capacity). Although this mechanism improves the efficiency of adding elements, it may also cause memory waste.

trimToSize()The method's purpose is toVectoradjust the internal array size to just enough to hold all current elements, releasing extra memory space.

Use Cases

  • WhenVectorWhen a large number of elements have been added and then some elements have been removed, causing the capacity to be much larger than the actual number of elements
  • In memory-sensitive applications, when memory usage needs to be optimized
  • When it is determined thatVectorthe content no longer changes, and you want to save memory

Method Implementation Principle

Source Code Analysis

The following isVectorin the classtrimToSize()implementation of the method:

Example

public synchronized void trimToSize() {
    modCount++;
    int oldCapacity = elementData.length;
    if (elementCount < oldCapacity) {
        elementData = Arrays.copyOf(elementData, elementCount);
    }
}

Implementation Steps

  1. Increment the modification countermodCount(used for fail-fast mechanism)
  2. Get the capacity of the current internal arrayoldCapacity
  3. If the current number of elementselementCountis less than the array capacity:
    • UseArrays.copyOf()to create a new array, the size iselementCount
    • Copy the original array contents to the new array
    • willelementDataPoint the reference to the new array

Notes

  • This method is synchronized (synchronized), thread-safe
  • After calling this method, if new elements are added again,Vectorit will still automatically expand
  • For largeVector, 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 an initial capacity of 10
        Vector<String> 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 of processing large amounts of data
        Vector<Integer> data = new Vector<>(10000);
       
        // Add a large amount of data
        for (int i = 0; i < 8000; i++) {
            data.add(i);
        }
       
        // After processing the 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

trimToSize()The time complexity of the method is O(n), where n isVectorthe number of elements in it. Because it needs to copy the original array to the new array.

Space Complexity

This method creates a new array, so it temporarily uses extra memory space, but eventually releases the excess memory.

Usage Recommendations

  • Do not call frequentlytrimToSize(), especially in loops
  • When it is determined thatVectorthe content basically no longer changes, call it
  • For smallVector, the optimization effect is not obvious and can be ignored

Comparison with Other Methods

Comparison with ArrayList's trimToSize()

ArrayListalso hastrimToSize()method, the implementation principle is similar, butArrayListits method is not synchronized.

Comparison with ensureCapacity()

Method Purpose Parameters Thread Safety
trimToSize() Shrink capacity to current size None Yes
ensureCapacity(int minCapacity) Ensure minimum capacity Minimum capacity value Yes

Summary

Vector.trimToSize()is a practical memory optimization method, especially suitable for the following scenarios:

  1. VectorAfter undergoing a large number of add and remove operations
  2. Environments with limited memory resources
  3. VectorWhen the content is determined to no longer change

When using it, note the following:

  • This method creates a new array and copies elements, which has some performance overhead.
  • If elements are added again after calling,Vectorit will still automatically expand
  • For smallVectoror frequently changingVector, may not need to use it

Reasonable usetrimToSize()can help optimize the memory usage efficiency of Java programs.

Java Vector Java Vector

Other Extensions