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 peration "
+ STACK);
}
}
輸出:
Initial Stack: [Welcome, To, Geeks, For, Geeks] Popped element: Geeks Popped element: For Stack after pop peration [Welcome, To, Geeks]
示例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]
相關用法
- Java Stack set()用法及代碼示例
- Java Stack contains()用法及代碼示例
- Java Stack get()用法及代碼示例
- Java Stack toArray(T[])用法及代碼示例
- Java Stack setElementAt()用法及代碼示例
- Java Stack removeRange()用法及代碼示例
- Java Stack isEmpty()用法及代碼示例
- Java Stack empty()用法及代碼示例
- Java Stack insertElementAt()用法及代碼示例
- Java Stack elementAt()用法及代碼示例
- Java Stack toString()用法及代碼示例
- Java Stack firstElement()用法及代碼示例
- Java Stack ensureCapacity()用法及代碼示例
- Java Stack subList()用法及代碼示例
- Java Stack size()用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Stack pop() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。