在Java中使用示例堆栈 ensureCapacity() 方法
如果需要, 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
Stack
stack = new Stack();
// 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
Stack
stack = new Stack();
// 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.