What is the Stack.trimToSize Method in Java?

The Stack class is a Last-In-First-Out (LIFO)The element inserted first is processed last and the element inserted last is processed first. stack of objects.

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

The size of a stack is the number of elements that it contains. The capacity is the total space that the stack has. Internally stack contains an array buffer into which the elements are stored. The size of this array buffer is the capacity of the stack. The size will be increased once the size of the stack 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 code below demonstrates how to use the trimToSize method:

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

Explanation

In the above code,

  • In line number 1: Imported the Stack class.

  • In line number 4: Created a new Stack object with the name stack.

  • From line number 5 to 7: Added three elements(1,2,3) to the stack object using the push method. Now the size of the stack is 3. The default capacity of the stack 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 stack becomes 3.

Free Resources