📜  Java中的 Stack capacity() 方法与示例

📅  最后修改于: 2022-05-13 01:54:18.396000             🧑  作者: Mango

Java中的 Stack capacity() 方法与示例

Stack 类capacity()方法用于获取此 Stack 的容量。这是此堆栈容器中存在的元素数量。

句法:

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 stack = new Stack();
  
        // 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 stack
            = new Stack();
  
        // 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