What is the Vector.trimToSize method in Java?

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index, and the size of a Vector can be increased or decreased.

Read more about Vector here.

The trimToSize method of the stack class will trim the vector’s capacity to the current size of the vector. This method can be used to minimize the storage of the vector.

The size of a vector is the number of elements that it contains. 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 vector size reaches the capacity or a configured minimum capacity.

Syntax

public void trimToSize()

This method doesn’t take any argument and doesn’t return any value.

Code

The below code demonstrates how to use the trimToSize method:

import java.util.Vector;
class TrimToSize {
public static void main( String args[] ) {
Vector<Integer> vector = new Vector<>();
vector.add(1);
vector.add(2);
vector.add(3);
System.out.println("The elements of the vector is " + vector);
System.out.println("The size of the vector is " + vector.size());
System.out.println("The capacity of the vector is " + vector.capacity());
vector.trimToSize();
System.out.println("\nThe elements of the vector is " + vector);
System.out.println("The size of the vector is " + vector.size());
System.out.println("The capacity of the vector is " + vector.capacity());
}
}

In the code above,

  • In line number 1: Imported the Vector class.

  • In line number 4: Created a new Vector object with the name vector.

  • From line number 4 to 7: Added four elements(1,2,3) to the vector object using the add method. Now the size of the vector is 3. And the default capacity of the vector object is 10.

  • In line number 13: We have used the trimToSize method to remove the extra space allocated. After calling this the capacity of the vector becomes 3.