What is the Vector.capacity method in Java?
The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index and the size of aVectorcan be increased or decreased. Read more aboutVectorhere.
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
Vectorclass. -
In line number 4: Created a new
Vectorobject with the namevector. -
In line number 6: Used the
capacity()method to get the capacity of the vector. This will return10that is the default capacity of thevector. -
In line number 8: Used the
forloop 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
10to20.