Java中的trimToSize()方法可以将Stack实例的容量调整为列表的当前容量。此方法用于将Stack实例修剪为包含的元素数量。
用法:
public void trimToSize()
参数:它不接受任何参数。
返回值:它不返回任何值。它将此Stack实例的容量调整为它包含的元素数。
以下示例程序旨在说明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());
}
}
输出:
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
示例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());
}
}
输出:
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
相关用法
- Java Vector trimToSize()用法及代码示例
- Java StringBuilder trimToSize()用法及代码示例
- Java StringBuffer trimToSize()用法及代码示例
- Java ArrayList trimToSize()用法及代码示例
- Java Stack contains()用法及代码示例
- Java Stack get()用法及代码示例
- Java Stack set()用法及代码示例
- Java Stack pop()用法及代码示例
- Java Stack lastElement()用法及代码示例
- Java Stack lastIndexOf()用法及代码示例
- Java Stack toArray(T[])用法及代码示例
- Java Stack setSize()用法及代码示例
- Java Stack toArray()用法及代码示例
- Java Stack subList()用法及代码示例
- Java Stack removeRange()用法及代码示例
注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Stack trimToSize() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。