隊列,先進先出 (FIFO)
Queue只有兩個操作:
- 把元素添加到隊列末尾
- 從隊列頭部取出元素
操作
代碼 | 作用 |
---|---|
int size() | 獲取隊列長度 |
boolean add(E)/boolean offer(E) | 添加元素到隊尾 |
E remove()/E poll() | 獲取隊首元素並從隊列中刪除 |
E element()/E peek() | 獲取隊首元素但並不從隊列中刪除 |
其中:
add, remove, element 添加失敗會 拋出異常
offer, poll, peek 添加失敗會 返回false或者NULL
創建
LinkedList即實現了List接口,又實現了Queue接口
// 這是一個List:
List<String> list = new LinkedList<>();
// 這是一個Queue:
Queue<String> queue = new LinkedList<>();
PriorityQueue
優先隊列,優先級高者在隊首
PriorityQueue默認按元素比較的順序排序(必須實現Comparable接口),也可以通過Comparator自定義排序算法(元素就不必實現Comparable接口
創建
Queue<String> q = new PriorityQueue<>(); //從小到大
//lambda表達式,從大到小
PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);
//自定義從大到小
PriorityQueue<Integer> pq= new PriorityQueue<Integer>(new Comparator<Integer>() {
public int compare(Integer x, Integer y) {
if (x < y) return 1;
if (x > y) return -1;
return 0;
}
});
Deque
雙端隊列
Java集合提供了接口Deque來實現一個雙端隊列,它的功能是:
- 既可以添加到隊尾,也可以添加到隊首;
- 既可以從隊首獲取,又可以從隊尾獲取。