Stack是java.util.Vector提供LIFO(后进先出)数据结构的类的扩展。此类提供了诸如push()和pop()的常用方法。peek方法用于获取堆栈的顶部元素,而无需删除该项目。
package org.nhooo.example.util; import java.util.Stack; public class StackExample { public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); // 我们将一些值存储在堆栈对象中。 for (int i = 0; i < 10; i++) { stack.push(i); System.out.print(i + " "); } System.out.println(""); //搜索堆栈中的项目。职位退回 //作为距堆栈顶部的距离。在这里我们搜索 // 在堆栈的第7行中的3号 // 堆栈。 int position = stack.search(3); System.out.println("Search result position: " + position); // 当前栈顶值 System.out.println("Stack top: " + stack.peek()); // 在这里,我们弹出所有堆栈对象项。 while (!stack.empty()) { System.out.print(stack.pop() + " "); } } }
代码段的结果:
0 1 2 3 4 5 6 7 8 9 Search result position: 7 Stack top: 9 9 8 7 6 5 4 3 2 1 0