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());
}
}