方法
| 方法声明 | 功能介绍 |
|---|---|
E push(E item) |
把元素放入栈中 |
boolean empty() |
判断堆栈是否为空 |
synchronized int search(Object o) |
返回对象在堆栈上的从1开始的位置 |
synchronized E pop() |
移除此堆栈顶部的对象并将该对象作为此函数的值返回 |
synchronized E peek() |
查看栈顶元素 |
案例题目
准备一个Stack集合,将数据11、22、33、44、55依次入栈并打印,
然后查看栈顶元素并打印,然后将栈中所有数据依次出栈并打印。
步骤
package top.testeru.listp;import java.util.Stack;public class StackDemo {public static void main(String[] args) {//1.准备Stack集合Stack stack = new Stack();System.out.println("stack = "+stack);//2.数据11、22、33、44、55依次入栈for (int i = 1; i < 6; i++) {Object push = stack.push(i * 11);System.out.println("入栈的元素是:" + push);System.out.println("栈中的元素有:" + stack);}//查看栈顶元素并打印Object peek = stack.peek();System.out.println("栈顶元素:"+ peek);//11 5//22 4//33 3//44 2//55 1int search = stack.search(55);System.out.println("----search:"+search);//栈中所有数据依次出栈并打印int len = stack.size();for (int i = 0; i < len; i++) {System.out.println("出栈的元素:"+ stack.pop());}//出完了之后打印,里面为空System.out.println(stack);}}
案例题目
再准备一个Stack对象,将数据从第一个栈中取出来放入第二个栈中,然后再从第二个栈中取出并打印。
import java.util.Stack;public class StackDemo2 {public static void main(String[] args) {//1.准备Stack集合Stack stack1 = new Stack();Stack stack2 = new Stack();System.out.println("stack1 = "+stack1);System.out.println("stack2 = "+stack2);for (int i = 1; i < 6; i++) {Object push = stack1.push(i * 11);System.out.println("stack1入栈元素有:" + push);}System.out.println("stack1:" + stack1);//数据从第一个栈中取出来 放入第二个栈中int len = stack1.size();for (int i = 0; i < len; i++) {//数据从第一个栈中取出来Object pop = stack1.pop();//放入第二个栈中stack2.push(pop);}System.out.println("stack2:" + stack2);//第二个栈中取出并打印len = stack2.size();for (int i = 0; i < len; i++) {System.out.println("stack2栈出栈的元素:"+ stack2.pop());}}}
