Java Vector trimToSize() Example

The trimToSize() method of java.util.Vector class trims the capacity of the vector to be the vector’s current size. If the capacity of the vector is larger than its current size, then the capacity is changed to equal the size by replacing its internal data array, kept in the field elementData with a smaller one.

Signature

public void trimToSize()

This method trims the capacity of the vector to be the vector’s current size.

Example

The following example shows the usage of java.util.Vector.trimToString() method.

import java.util.Vector;

public class TrimToSizeMethodVectorExample {
    public static void main(String args[])
    {
        // create an empty Vector
        Vector vector1 = new Vector();
        
        // use add() method to add elements to the Vector
        vector1.add("Element1");
        vector1.add("Element2");
        vector1.add("Element3");
        vector1.add("Element4");
        
        //Lets check the capacity of the vector
        System.out.println("Capacity of the vector is : "+vector1.capacity());
        
        //triming the size
        vector1.trimToSize();
        
        //Size after trimming
        System.out.println("Size of the vector after trimming : "+vector1.capacity());
    }
}

Output

Capacity of the vector is : 10
Size of the vector after trimming : 4

Leave a Reply

Your email address will not be published. Required fields are marked *