In this source code example, we will demonstrate the usage of the Vector capacity() method in Java with an example.
Vector java.util.Vector.capacity() Method
The java.util.Vector.capacity() method in Java is used to get the capacity of the Vector or the length of the array present in the Vector.
java.util.Vector.capacity() Method Example
The below program illustrates the working of java.util.Vector.capacity() method:
import java.util.*;
public class VectorDemo {
public static void main(String args[])
{
// Creating an empty Vector
Vector programLangs = new Vector();
// Use add() method to add elements in the vector
programLangs.add("C");
programLangs.add("C++");
programLangs.add("Java");
programLangs.add("Python");
programLangs.add("Go");
// Output the present vector
System.out.println("The vector is: " + programLangs);
// Displaying the capacity of Vector
System.out.println("The capacity is: " + programLangs.capacity());
}
}
Output:
The vector is: [C, C++, Java, Python, Go] The capacity is: 10
Example 2:
import java.util.Vector;
/*
* Example of capacity() method
*/
public class VectorExample
{
public static void main(String[] args)
{
Vector vector = new Vector();
System.out.println("vector : " + vector);
System.out.println("vector size : " + vector.size());
/*
* Returns the current capacity of this vector.
*/
int capacity = vector.capacity();
System.out.println("capacity : " + capacity + "\n");
for (int i = 0; i < 11; i++)
{
vector.add(i+1);
}
System.out.println("vector : " + vector);
System.out.println("vector size : " + vector.size());
capacity = vector.capacity();
System.out.println("capacity : " + capacity + "\n");
int j = vector.size()+1;
for (int i = 0; i < 11; i++)
{
vector.add(i+j);
}
System.out.println("vector : " + vector);
System.out.println("vector size : " + vector.size());
capacity = vector.capacity();
System.out.println("capacity : " + capacity + "\n");
}
}
Output:
vector : [] vector size : 0 capacity : 10 vector : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] vector size : 11 capacity : 20 vector : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] vector size : 22 capacity : 40