Java Vector trimToSize() Method Tutorial

In this section, we will learn what the Vector trimToSize() method is and how to use it in Java.

What is Java Vector trimToSize() Method?

The capacity of a Vector object (the number of elements it can take) is dynamic and always higher than the current number of elements in such an object.

For example, if there are 10 elements already in a vector object, the capacity of that vector might be at 20 or more.

Now if the elements of a vector object are already set and there are no more elements for that object, having a capacity higher than the number of elements would be a waste of memory!

For this reason, we can use the trimToSize() method to trim the size of a vector to its current number of elements and basically free the unnecessary memory space.

Java Vector trimToSize() Method Syntax:

public void trimToSize()

trimToSize() Method Parameters:

The method does not take any argument.

trimToSize() Method Return Value:

The return value of this method is void.

trimToSize() Method Exceptions:

The method does not throw an exception.

Example: using Vector trimToSize() method

import java.util.Vector; 
public class Main {

    public static void main(String[] args){
        
        Vector <String> vector = new Vector<>();
        vector.add("Jack");
        vector.add("Omid");
        vector.add("Ellen");
        vector.add("John");

        System.out.println("The current capacity of the vector object: "+vector.capacity());
        vector.trimToSize();
        System.out.println("The size of the vector object after trimming the size: "+ vector.capacity());

    }
}

Output:

The current capacity of the vector object: 10

The size of the vector object after trimming the size: 4

The current capacity of the vector object in this example is 10, while there are only 4 elements in its body. But after we’ve called the trimToSize() method on the vector object, the size trimmed to 4 which is equal to the number of elements that are already in the object.

Leave a Reply