Stack是栈,符合LIFO(last in first out)原则。所以对于类似执行了一连串的命令,然后需要撤销的这种场景,使用它比较合适。
Stack集成Vector,所以用法跟Vector和List等集合类似。
Stack有些独有的方法:
empty() : 检查Stack集合是否是空了,空的话返回true,否则返回false;
peek() : 返回Stack集合里最顶端的对象,也就是最后加入到集合中的对象。
pop() : 返回Stack集合里面最顶端的对象,并将该对象从集合中弹出或者删除,执行后,集合的大小-1.
push() : 往Stack集合中添加对象
search() : 返回查询到集合中第一个对象的位置,用的比较的方法也是跟集合中的对象进行equals比较
简单的示例如下:
public class TestStack {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("1111");
stack.push("2222");
stack.push("3333");
stack.push("4444");
System.out.println(stack.peek());
System.out.println(System.lineSeparator());
System.out.println(stack.search("4444"));
System.out.println(System.lineSeparator());
for(int i=0;i<4;i++){
System.out.println("i="+i+" stack="+stack.pop());
System.out.println(stack.empty()?"":stack.peek());
}
System.out.println(System.lineSeparator());
System.out.println(stack.empty());
}
}
输出结果如下:
4444
1
i=0 stack=4444
3333
i=1 stack=3333
2222
i=2 stack=2222
1111
i=3 stack=1111
true