Java Stack capacity()方法与实例
堆栈类的capacity()方法是用来获取这个堆栈的容量。也就是这个堆栈容器中存在的元素数量。
语法
public int capacity()
参数: 该函数接受一个参数E obj,它是要被添加到堆栈末端的对象。
返回值: 该方法返回整数值,该值是堆栈的容量。
下面的程序说明了Java.util.Stack.capacity()方法。
例子1:
// Java code to illustrate boolean capacity()
import java.util.*;
import java.util.ArrayList;
public class GFG {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use add() method to add elements in the Stack
stack.add("Geeks");
stack.add("for");
stack.add("Geeks");
stack.add("10");
stack.add("20");
// Displaying the Stack
System.out.println("The Stack is: " + stack);
// checking capacity
System.out.println("Capacity: "
+ stack.capacity());
}
}
输出:
The Stack is: [Geeks, for, Geeks, 10, 20]
Capacity: 10
例2:
// Java code to illustrate
// boolean add(Object element)
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> stack
= new Stack<Integer>();
// Use add() method
// to add elements in the Stack
stack.add(10);
stack.add(20);
stack.add(30);
stack.add(40);
stack.add(50);
// Displaying the Stack
System.out.println("The Stack is: " + stack);
// checking capacity
System.out.println("Capacity: "
+ stack.capacity());
}
}
输出:
The Stack is: [10, 20, 30, 40, 50]
Capacity: 10
极客教程