如有必要,Java.util.Stack类的ensureCapacity()方法会增加此Stack实例的容量,以确保它至少可以容纳最小容量参数指定的元素数量。
用法:
public void ensureCapacity(int minCapacity)
参数:该方法将所需的最小容量作为参数。
以下示例说明了ensureCapacity()方法。
示例1:
// Java program to demonstrate
// ensureCapacity() method for Integer value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// 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);
// ensure that the Stack
// can hold upto 5000 elements
// using ensureCapacity() method
stack.ensureCapacity(5000);
// Print
System.out.println("Stack can now"
+ " surely store upto"
+ " 5000 elements.");
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Stack: [10, 20, 30, 40] Stack can now surely store upto 5000 elements.
示例2:
// Java program to demonstrate
// ensureCapacity() method for String value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// Creating object of Stack<Integer>
Stack<String>
stack = new Stack<String>();
// adding element to stack
stack.add("A");
stack.add("B");
stack.add("C");
stack.add("D");
// Print the Stack
System.out.println("Stack: "
+ stack);
// ensure that the Stack
// can hold upto 400 elements
// using ensureCapacity() method
stack.ensureCapacity(400);
// Print
System.out.println("Stack can now"
+ " surely store upto"
+ " 400 elements.");
}
catch (NullPointerException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出:
Stack: [A, B, C, D] Stack can now surely store upto 400 elements.
相关用法
- Java Vector ensureCapacity()用法及代码示例
- Java ArrayList ensureCapacity()用法及代码示例
- Java StringBuffer ensureCapacity()用法及代码示例
- Java StringBuilder ensureCapacity()用法及代码示例
- Java Stack set()用法及代码示例
- Java Stack pop()用法及代码示例
- Java Stack get()用法及代码示例
- Java Stack contains()用法及代码示例
- Java Stack toString()用法及代码示例
- Java Stack search()用法及代码示例
- Java Stack insertElementAt()用法及代码示例
- Java Stack setElementAt()用法及代码示例
- Java Stack retainAll()用法及代码示例
- Java Stack size()用法及代码示例
- Java Stack trimToSize()用法及代码示例
注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Stack ensureCapacity() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。