Java.util.Stack.push(E element)方法用於將元素壓入堆棧。元素被推入堆棧的頂部。
用法:
STACK.push(E element)
參數:該方法接受一個類型為Stack的參數element ,表示要壓入堆棧的元素。
返回值:該方法返回傳遞的參數。
以下示例程序旨在說明Java.util.Stack.push()方法:
示例1:將String元素添加到Stack中。
// Java code to illustrate push() method
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> STACK = new Stack<String>();
// Use push() to add elements into the Stack
STACK.push("Welcome");
STACK.push("To");
STACK.push("Geeks");
STACK.push("For");
STACK.push("Geeks");
// Displaying the Stack
System.out.println("Initial Stack: " + STACK);
// Pushing elements into the stack
STACK.push("Hello");
STACK.push("World");
// Displaying the final Stack
System.out.println("Final Stack: " + STACK);
}
}
輸出:
Initial Stack: [Welcome, To, Geeks, For, Geeks] Final Stack: [Welcome, To, Geeks, For, Geeks, Hello, World]
示例2:將Integer元素添加到堆棧中。
// Java code to illustrate push() method
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<Integer> STACK = new Stack<Integer>();
// Use push() to add elements into the Stack
STACK.push(10);
STACK.push(15);
STACK.push(30);
STACK.push(20);
STACK.push(5);
// Displaying the Stack
System.out.println("Initial Stack: " + STACK);
// Pushing elements into the Stack
STACK.push(1254);
STACK.push(4521);
// Displaying the final Stack
System.out.println("Final Stack: " + STACK);
}
}
輸出:
Initial Stack: [10, 15, 30, 20, 5] Final Stack: [10, 15, 30, 20, 5, 1254, 4521]
相關用法
- Java LinkedList push()用法及代碼示例
- Java LinkedBlockingDeque push()用法及代碼示例
- Java ArrayDeque push()用法及代碼示例
- Java ConcurrentLinkedDeque push()用法及代碼示例
- Java BlockingDeque push()用法及代碼示例
- Java Stack set()用法及代碼示例
- Java Stack contains()用法及代碼示例
- Java Stack pop()用法及代碼示例
- Java Stack get()用法及代碼示例
- Java Stack lastIndexOf()用法及代碼示例
- Java Stack setSize()用法及代碼示例
- Java Stack toArray()用法及代碼示例
- Java Stack subList()用法及代碼示例
- Java Stack removeRange()用法及代碼示例
- Java Stack listIterator(int)用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Stack push() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。