Java中的Stack push()方法
Java.util.Stack.push(E element)方法用于将元素推入栈中。该元素被推到栈的顶部。
语法:
STACK.push( _E element_ )
参数: 该方法接受一个参数 element ,类型为Stack,指的是要推入堆栈的元素。
返回值: 该方法返回传递的参数。它也接受null值,不像ArrayDeque.push()在进行相同操作时会抛出java.lang.NullPointerException异常。
下面的程序说明了Java.util.Stack.push()方法:
程序1: 将字符串元素添加到堆栈中。
// Java Code to illustrate push() Method
import java.util.*;
// Main class
public class StackDemo {
// Main driver method
public static void main(String args[])
{
// Creating an empty Stack
Stack STACK = new Stack();
// Adding elements into the stack
// using push() method
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<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);
STACK.push(null);
// 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]