The trimToSize() method of Stack in Java trims the capacity of an Stack instance to be the list’s current capacity. This method is used to trim an Stack instance to the number of elements it contains.
Syntax:
public void trimToSize()
Parameter: It does not accepts any parameter.
Return Value: It does not returns any value. It trims the capacity of this Stack instance to the number of the element it contains.
Below program illustrate the trimToSize() method:
import java.util.Stack;
public class GFG {
public static void main(String[] args)
{
Stack<Integer>
stack = new Stack<Integer>();
stack.add( 10 );
stack.add( 20 );
stack.add( 30 );
stack.add( 40 );
System.out.println( "Stack: " + stack);
System.out.println( "Current capacity of Stack: "
+ stack.capacity());
stack.ensureCapacity( 15 );
System.out.println( "New capacity of Stack: "
+ stack.capacity());
stack.trimToSize();
System.out.println( "Current capacity of Stack"
+ " after use of trimToSize() method: "
+ stack.capacity());
}
}
|
Output:
Stack: [10, 20, 30, 40]
Current capacity of Stack: 10
New capacity of Stack: 20
Current capacity of Stack after use of trimToSize() method: 4
Example 2:
import java.util.*;
public class collection {
public static void main(String args[])
{
Stack<String> stack
= new Stack<String>();
stack.add( "Welcome" );
stack.add( "To" );
stack.add( "Geeks" );
stack.add( "For" );
stack.add( "Geeks" );
System.out.println( "Stack: " + stack);
System.out.println( "Current capacity of Stack: "
+ stack.capacity());
stack.ensureCapacity( 20 );
System.out.println( "New capacity of Stack: "
+ stack.capacity());
stack.trimToSize();
System.out.println( "Current capacity of Stack"
+ " after use of trimToSize() method: "
+ stack.capacity());
}
}
|
Output:
Stack: [Welcome, To, Geeks, For, Geeks]
Current capacity of Stack: 10
New capacity of Stack: 20
Current capacity of Stack after use of trimToSize() method: 5