El método trimToSize() de Stack en Java recorta la capacidad de una instancia de Stack para que sea la capacidad actual de la lista. Este método se utiliza para recortar una instancia de Stack al número de elementos que contiene.
Sintaxis:
public void trimToSize()
Parámetro: No acepta ningún parámetro.
Valor devuelto: No devuelve ningún valor. Recorta la capacidad de esta instancia de Stack al número del elemento que contiene.
El siguiente programa ilustra el método trimToSize():
// Java code to demonstrate the working of // trimToSize() method in Stack // for Stack functions import java.util.Stack; public class GFG { public static void main(String[] args) { // Creating object of Stack<Integer> Stack<Integer> stack = new Stack<Integer>(); // adding element to stack stack.add(10); stack.add(20); stack.add(30); stack.add(40); // Print the Stack System.out.println("Stack: " + stack); // Print the current capacity of Stack System.out.println("Current capacity of Stack: " + stack.capacity()); // Change the capacity to 15 stack.ensureCapacity(15); // Print the current capacity of Stack System.out.println("New capacity of Stack: " + stack.capacity()); // trims the capacity to the number of elements stack.trimToSize(); // Print the current capacity of Stack System.out.println("Current capacity of Stack" + " after use of trimToSize() method: " + stack.capacity()); } }
Producción:
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
Ejemplo 2:
// Java program to demonstrate // Stack toString() method import java.util.*; public class collection { public static void main(String args[]) { // Creating an Empty Stack Stack<String> stack = new Stack<String>(); // Use add() method // to add elements to the Collection stack.add("Welcome"); stack.add("To"); stack.add("Geeks"); stack.add("For"); stack.add("Geeks"); // Print the Stack System.out.println("Stack: " + stack); // Print the current capacity of Stack System.out.println("Current capacity of Stack: " + stack.capacity()); // Change the capacity to 20 stack.ensureCapacity(20); // Print the current capacity of Stack System.out.println("New capacity of Stack: " + stack.capacity()); // trims the capacity to the number of elements stack.trimToSize(); // Print the current capacity of Stack System.out.println("Current capacity of Stack" + " after use of trimToSize() method: " + stack.capacity()); } }
Producción:
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