Java Stack push()方法
Java.util.Stack.push(E element)方法用于将一个元素推入堆栈。该元素会被推到堆栈的顶部。
语法
STACK.push(E element)
参数: 该方法接受一个Stack类型的参数element,指的是要被推入堆栈的元素。
返回值: 该方法返回所传递的参数。 它也接受空值,不像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& lt;
String& gt;
STACK = new Stack& lt;
String& gt;
();
// Adding elements into the stack
// using push() method
STACK.push(" Welcome & quot;);
STACK.push(" To & quot;);
STACK.push(" Geeks & quot;);
STACK.push(" For & quot;);
STACK.push(" Geeks & quot;);
// Displaying the Stack
System.out.println(" Initial Stack
: "
+ STACK);
// Pushing elements into the stack
STACK.push(" Hello & quot;);
STACK.push(" World & quot;);
// 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]
极客教程