What is the Vector.capacity method in Java?

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index and the size of a Vector can be increased or decreased. Read more about Vector here.

The capacity method of the Vector class will return the current capacity of this vector.

The capacity is the total space that the vector has. Internally vector contains an array buffer into which the elements are stored. The size of this array buffer is the capacity of the vector. The size will be increased once the size of the vector reaches the capacity or a configured minimum capacity.

The default capacity of the vector is 10. The default capacity of the vector and the amount by which the capacity should be increased on overflow can be configured during Vector object creation using the below constructor.

new Vector(int intialCapacity, int capacityIncrement)

Syntax

public int capacity()

This method doesn’t take any argument.

This method returns an integer value representing the capacity of this vector.

Code

The below code demonstrates how to use the capacity method:

import java.util.Vector;
class Capacity {
public static void main( String args[] ) {
Vector<Integer> vector = new Vector<>();
System.out.println("The elements of the vector is " + vector);
System.out.println("The default capacity of the vector is " + vector.capacity());
for(int i = 0; i < 10; i++){
vector.add(i);
}
System.out.println("\nThe elements of the vector is " + vector);
System.out.println("The capacity of the vector is " + vector.capacity());
vector.add(10);
System.out.println("\nThe elements of the vector is " + vector);
System.out.println("The capacity of the vector is " + vector.capacity());
}
}

Explanation

In the above code,

  • In line number 1: Imported the Vector class.

  • In line number 4: Created a new Vector object with the name vector.

  • In line number 6: Used the capacity() method to get the capacity of the vector. This will return 10 that is the default capacity of the vector.

  • In line number 8: Used the for loop to add 10 elements to the vector.

Now the capacity of the vector is 10 and it contains 10 elements. If we add one more element to it then the number of elements in the vector will be greater than capacity so during the element insert the capacity is incremented by current size + 10.

  • In line number 14: We added one more element to the vector, here the size has already reached the capacity so the capacity is increased from 10 to 20.

Free Resources