Java Utility Library

Java Vector - ensureCapacity() Method



The java.util.Vector.ensureCapacity() method is used to increase the capacity of the vector, if necessary, to ensure that it can hold at least the number of components specified by the minimum capacity argument.

If the current capacity of the vector is less than minCapacity, then its capacity is increased by replacing its internal data array, kept in the field elementData, with a larger one. The size of the new data array will be the old size plus capacityIncrement, unless the value of capacityIncrement is less than or equal to zero, in which case the new capacity will be twice the old capacity; but if this new size is still smaller than minCapacity, then the new capacity will be minCapacity.

Syntax

public void ensureCapacity(int minCapacity)

Parameters

minCapacity Specify the desired minimum capacity.

Return Value

void type.

Exception

NA.

Example:

In the example below, the java.util.Vector.ensureCapacity() method is used to increase the capacity of the vector.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a vector
    Vector<Integer> MyVec = new Vector<Integer>(3);

    //populating vector
    MyVec.add(10);
    MyVec.add(20);
    MyVec.add(30);

    //print the capacity of the vector
    System.out.println("MyVec capacity: " + MyVec.capacity());

    //increase the capacity of the vector
    MyVec.ensureCapacity(10);

    //print the capacity of the vector
    System.out.println("MyVec capacity: " + MyVec.capacity());
  }
}

The output of the above code will be:

MyVec capacity: 3
MyVec capacity: 10

❮ Java.util - Vector