java.util.Vector.ensureCapacity() Method


Description

The ensureCapacity(int minCapacity) method is used to increases the capacity of this vector, if necessary.This is to ensure that the vector can hold at least the number of components specified by the minimum capacity argument.If the current capacity of this 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.If the value of capacityIncrement is less than or equal to zero then 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.

Declaration

Following is the declaration for java.util.Vector.ensureCapacity() method

public void ensureCapacity(int minCapacity)

Parameters

minCapacity − This is the desired minimum capacity.

Return Value

It returns void.

Exception

NA

Example

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

package com.tutorialspoint;

import java.util.Vector;

public class VectorDemo {
   public static void main(String args[]) {

      // create a vector of initial capacity 5 
      Vector vec = new Vector(5);

      for (int i = 0; i < 10; i++) {
         vec.add(0,i);
      }
      System.out.println("Content of the vector: "+vec);
      System.out.println("Size of the vector: "+vec.size());  

      // ensure the capacity of the vector and add elements
      vec.ensureCapacity(40);
      
      for (int i = 0; i < 10; i++) {
         vec.add(0,i);
      }    
      System.out.println("Content of the vector after increasing the size: "+vec);
      System.out.println("Size of the vector after increase: "+vec.size());
   }    
}

Let us compile and run the above program, this will produce the following result.

Content of the vector: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Size of the vector: 10
Content of the vector after increasing the size: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Size of the vector after increase: 20
java_util_vector.htm
Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements