Java program for Vector.capacity() Method

JAVA program for Vector.capacity() Method

This JAVA program is to demonstrate the use of Vector.capacity() method.

The capacity() method returns the current capacity of the vector as an integer value. By default, the capacity of the vector is 10.

Dry Run of the Program

Initialize the vector object.  We can use different constructors as well.

Insert elements in the vector using add() method or addElement() method.

You can see int the output given below that at any point of time the capacity of vector is 10. On inserting the 11th element the capacity of vector increments by 10 thus new capacity of vector is 20.

Size of vector gives length of the vector. Use size() method to find size of the vector.

trimToSize() method trims the capacity of the Vector.

Program

import java.util.*;

class v1
{
	public static void main(String args[])
	{
		Vector<Integer> v = new Vector<Integer>();  //Try out the different constructors as practice				
		v.add(1);
		v.add(2);
		v.add(3);
		v.add(4);
		v.add(5);
		v.add(6);
		v.add(7);
		System.out.println("After inserting 7 elements the capacity of vector = "+v.capacity());
		System.out.println("After inserting 7 elements the size of vector = "+v.size());
		v.add(8);
		v.add(9);
		v.add(10);	
		v.add(11);
		System.out.println("After inserting the 11th element the size of vector = "+v.size());		
		System.out.println("After inserting the 11th element the capacity of vector = "+v.capacity());
		v.trimToSize(); //Making capacity of the vector equal to the size of the vector
		System.out.println("After inserting the 11th element the capacity(Using trimToSize()) of vector = "+v.capacity());
	}
}

Output

Share Me!