What is the Stack.trimToSize Method in Java?
The
Stackclass is astack of objects. Last-In-First-Out (LIFO) The element inserted first is processed last and the element inserted last is processed first.
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
sizeof a stack is the number of elements that it contains. Thecapacityis the total space that the stack has. Internally stack contains anarray bufferinto which the elements are stored. The size of thisarray bufferis 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
Stackclass. -
In line number 4: Created a new
Stackobject with the namestack. -
From line number 5 to 7: Added three elements(
1,2,3) to thestackobject using thepushmethod. Now the size of thestackis3. The default capacity of the stack object is 10. -
In line number 13: We have used the
trimToSizemethod to remove the extra space allocated. After calling this, the capacity of thestackbecomes3.