Java Vector ensureCapacity(int minCapacity) Method Example

The ensureCapacity(int minCapacity) method of java.util.Vector class increases the capacity of the vector, if necessary.This is to ensure that the vector can hold at least the number of components specified by the minimum capacity argument.

Signature

public void ensureCapacity(int minCapacity) 

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.

Example

The following example shows the usage of java.util.Vector.ensureCapacity(minCapacity) method.

import java.util.Enumeration;
import java.util.Vector;

public class EnsureCapacityMethodVectorExample 
{
    public static void main(String args[])
    {
	    // Create vector1 with initial capacity of 5
	    Vector vector1 = new Vector(5);
	    
	    //printing the current capacity of the vector
	    System.out.println("Current capacity of the vector is : "+vector1.capacity());
	    
	    //adding elements to Vector using add()
	    for (int i = 0; i < 10; i++) 
	    {
	        vector1.add(i,"Element"+i);
	    }
	    System.out.println("Elements of the vector1 "+vector1);
	    //Capacity and size of the vector after adding
	    System.out.println("Current Capacity : "+vector1.capacity());
	    System.out.println("Current Size : "+vector1.size());
	    
	    //Lets use ensureCapacity to set the capacity for the vector
	    vector1.ensureCapacity(50);
	    //Now lets check the capacity again
	    System.out.println("Capacity of the vector1 : "+vector1.capacity());
    }
}

Output

Current capacity of the vector is : 5
Elements of the vector1 [Element0, Element1, Element2, Element3, Element4, Element5, Element6, Element7, Element8, Element9]
Current Capacity : 10
Current Size : 10
Capacity of the vector1 : 50

Leave a Reply

Your email address will not be published. Required fields are marked *