队列,先进先出 (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来实现一个双端队列,它的功能是:
- 既可以添加到队尾,也可以添加到队首;
- 既可以从队首获取,又可以从队尾获取。