Stack栈
栈是一种先进后出的数据结构 浏览器的后退、编辑器的撤销、安卓Activity的返回等都属于栈的功能。
在Java集合中提供有Stack类,这个类时Vector的子类。需要注意的是,使用这个类的时候使用的不是Vector类中的方法,并且在使用时不要进行向上转型。因为要操作的方法不是又List定义的,而是由Stack定义的。
- 入栈 : public E push(E item)
- 出栈 : public synchronized E pop()
- 观察栈顶元素 : public synchronized E peek()
范例:观察出入栈操作
import java.util.Stack;
public class SkackDemo {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("hello");
stack.push("I'm");
stack.push("fish");
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
//空栈再次出栈会抛出空栈异常
// System.out.println(stack.pop());
}
}
空栈异常
Queue队列
Stack是先进后出,与之对应的Queue是先进先出。
在java.util包中使用Queue来实现队列处理操作。Queue接口有一个子类LinkedList。来看Queue接口继承关系:
使用Queue接口主要是进行先进先出的实现,在这个接口里面有如下的方法:
按照队列取出内容: public E poll();
范例:观察Queue的poll操作
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
queue.add("Hello");
queue.add("I'm");
queue.add("fish");
System.out.println(queue.peek());
System.out.println(queue.poll());
System.out.println(queue.poll());
System.out.println(queue.poll());
//取完数据继续poll返回null
System.out.println(queue.poll());
}
}