capacity() and size() of Vector in Java

In Java's java.util.Vector class, the capacity() and size() methods serve different purposes and provide information about distinct aspects of the vector.

capacity()

The capacity() method returns the current capacity of the vector. Capacity represents the total number of elements the vector can hold without resizing. Initially, when a vector is created, it has a default capacity. However, as elements are added to the vector, its capacity may be automatically increased to accommodate additional elements. The capacity() method allows you to check the current capacity of the vector, which may be larger than the actual number of elements present.

size()

The size() method, on the other hand, returns the current number of elements in the vector. It represents the actual count of elements that have been added to the vector. Unlike capacity, the size of the vector changes dynamically as elements are added or removed. By invoking size(), you can obtain the precise count of elements in the vector at a given point in time.

Example
import java.util.*; class TestClass { public static void main (String[] args) throws java.lang.Exception { //create new Vector Object Vector vcTr = new Vector(); System.out.println("Vector Size: " + vcTr.size()); vcTr.setSize(2); System.out.println("Vector Size: " + vcTr.size()); vcTr.addElement("Sunday"); vcTr.addElement("Monday"); vcTr.addElement("Wednesday"); System.out.println("Vector Size: " + vcTr.size()); System.out.println("Vector Capacity: " + vcTr.capacity()); } }
Output
Vector Size: 0 Vector Size: 2 Vector Size: 5 Vector Capacity: 10

Conclusion

The capacity() method in java.util.Vector returns the total capacity of the vector, while the size() method provides the current count of elements stored in the vector.