📜  Java中的栈 push() 方法

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

Java中的栈 push() 方法

Java.util.Stack.push(E element) 方法用于将元素推入堆栈。该元素被推到堆栈的顶部。

句法:

STACK.push(E element)

参数:该方法接受一个堆栈类型的参数元素,并引用要压入堆栈的元素。

返回值:该方法返回传递的参数。

下面的程序说明了Java.util.Stack.push() 方法:

程序 1:将字符串元素添加到堆栈中。

// Java code to illustrate push() method
  
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack STACK = new Stack();
  
        // 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:将整数元素添加到堆栈中。

// Java code to illustrate push() method
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack STACK = new Stack();
  
        // 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]