Java Vector trimToSize( ) Method with Example

In the previous article, we have discussed about Java Vector lastElement() Method with Example

In this article, we are going to see the use of the Java Vector trimToSize( ) Method along with examples.

Java Vector trimToSize( ) Method with Example

This java.util.Vector.trimToSize() method trims the minimum capacity of the vector to match the vector size.

Syntax:

vectorName.trimToSize( )

Where,

  • vectorName refers to the name of the Vector.

Approach:

  • Create a vector of string data type and add some elements to it.
  • Print the elements.
  • Now trim the capacity of the vector to match its size by using the trimToSize( ) method.
  • Print the vector capacity after trimming the vector.

Program:

import java.util.*;
public class Main
{
   public static void main(String[] args) 
   {
       // Create a Vector of string datatype
       Vector<String> vec = new Vector<String>();
       // Adding some elements to the vector
       vec.add("One");
       vec.add("Two");
       vec.add("Three");
       vec.add("Four");
       vec.add("Five");
       vec.add("Six");
       vec.add("Seven");
       // Prints the vector elements
       System.out.println("The vector elements are "+vec);
       // Prints the capacity of the vector
       System.out.println("The capacity of the vector is "+vec.capacity());
       // Trims the vector capacity to match its size
       vec.trimToSize();
       // Prints the capacity of the vector
       System.out.println("The capacity of the vector after trimming "+vec.capacity());
   }
}
Output:

The vector elements are [One, Two, Three, Four, Five, Six, Seven]
The capacity of the vector is 10
The capacity of the vector after trimming 7

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Related Java Programs: