Java Stack pop()方法
Java中的Java.util.Stack.pop()方法用于从堆栈中弹出一个元素。该元素从堆栈的顶部被弹出,并从相同的地方被删除。
语法
STACK.pop()
参数: 该方法不接受任何参数。
返回值: 该方法返回存在于栈顶的元素,然后将其删除。
异常: 如果栈是空的,该方法会抛出EmptyStackException。
以下程序说明了Java.util.Stack.pop()方法:
程序1 :
// Java code to illustrate pop()
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> STACK = new Stack<String>();
// Use add() method to add elements
STACK.push("Welcome");
STACK.push("To");
STACK.push("Geeks");
STACK.push("For");
STACK.push("Geeks");
// Displaying the Stack
System.out.println("Initial Stack: " + STACK);
// Removing elements using pop() method
System.out.println("Popped element: " +
STACK.pop());
System.out.println("Popped element: " +
STACK.pop());
// Displaying the Stack after pop operation
System.out.println("Stack after pop operation "
+ STACK);
}
}
示例2
// Java code to illustrate pop()
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
STACK.push(10);
STACK.push(15);
STACK.push(30);
STACK.push(20);
STACK.push(5);
// Displaying the Stack
System.out.println("Initial Stack: " + STACK);
// Removing elements using pop() method
System.out.println("Popped element: " +
STACK.pop());
System.out.println("Popped element: " +
STACK.pop());
// Displaying the Stack after pop operation
System.out.println("Stack after pop operation "
+ STACK);
}
}
输出
Initial Stack: [10, 15, 30, 20, 5]
Popped element: 5
Popped element: 20
Stack after pop operation [10, 15, 30]
极客教程