Difference between capacity() and size() in Vector

The difference between capacity() and size() in java.util.Vector is that capacity() returns how many elements it can store whereas the size() gives the no.of elements in the Vector at the time of method call.
Capacity of a vector is usually declared within the constructor itself. An example will give better understand.

import java.util.*;
class CapacitySize
{
public static void main(String args[])
{
Vector<String> v=new Vector<String>(10);
v.setSize(3);
v.add("java-demos.blogspot.com");
v.add("Gowtham Gutha");
System.out.println("The capacity of the vector is "+v.capacity());
System.out.println("The size of the vector is "+v.size());
}
}

In the above example, the size of the vector is set to 10 (if you use the default constructor, the default vector size then will be 10 only). Next, the size is set to 3 and then added 2 elements to it. When, the size is printed, 5(3+2) is printed. Because 2 elements are added after the size is set to 3. A vector is like a dynamic array which can be extended. The capacity is the no.of elements that the vector can store is 10 because 10 is passed in the creation, 10 will be printed.

Sample Output


The capacity of the vector is 10
The size of the vector is 5
92YF2PBFC8XG


Posted by at on

Tags: Java Utilities, Vector,