當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stack push()用法及代碼示例


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]


相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Stack push() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。