Java Vector ensureCapacity() Method

Java Vector Java Vector

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:

  1. If the currentVectorcapacity of the Vector is less than the specified minimum capacity, increase its capacity
  2. If the current capacity is already large enough, it does nothing.
  3. By preallocating enough space, the number of expansions when adding elements later can be reduced.

Usage Example

Basic Usage

Example

import java.util.Vector;

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

import java.util.Vector;

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:

  1. Check whether the current capacity is less than the minimum capacity specified by the parameter
  2. If so, create a new larger array
  3. Copy the existing elements to the new array
  4. 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:

  1. By default,Vectorthe initial capacity is 10
  2. When expansion is needed, the capacity doubles by default (that is, new capacity = old capacity * 2)
  3. You can also specify a different growth amount.

Notes

  1. ensureCapacity()It only increases capacity and never decreases it.
  2. If the specified minimum capacity is less than the current capacity, the method does nothing.
  3. This method does not changeVectorthe Vector's size(); it only affects capacity().
  4. 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).

Java Vector Java Vector

Other Extensions