总结:
队列Queue实现了一个先进先出(FIFO)的数据结构:
- 通过add()/offer()方法将元素添加到队尾;
- 通过remove()/poll()从队首获取元素并删除;
- 通过element()/peek()从队首获取元素但不删除。
要避免把null添加到队列
队列(Queue)是一种经常使用的集合。Queue实际上是实现了一个先进先出(FIFO:First In First Out)的有序表。它和List的区别在于,List可以在任意位置添加和删除元素,而Queue只有两个操作:
- 把元素添加到队列末尾;
- 从队列头部取出元素。
对于具体的实现类,有的Queue有最大队列长度限制,有的Queue没有。注意到添加、删除和获取队列元素总是有两个方法,这是因为在添加或获取元素失败时,这两个方法的行为是不同的。我们用一个表格总结如下:
| throw Exception | 返回false或null | |
|---|---|---|
| 添加元素到队尾 | add(E e) | boolean offer(E e) |
| 取队首元素并删除 | E remove() | E poll() |
| 取队首元素但不删除 | E element() | E peek() |
public class QueueDemo {public static void printQ(Queue queue){while (queue.peek()!=null){ //note——看看queue.poll()会出现什么效果?System.out.print(queue.poll()+" ");System.out.print("剩余的元素:"+queue);System.out.println();}System.out.println();}public static void main(String[] args) {LinkedList<String> queue = new LinkedList<>();Random rand = new Random();String str = "abcdefghl";String[] strings = str.split("");for (int i = 0; i < strings.length; i++) {queue.offer(strings[i]);}System.out.println("queue: "+queue);printQ(queue);Queue<Character> qc = new LinkedList<>();for (char c : "Brontsaurus".toCharArray()){qc.offer(c);}System.out.println(qc);}}输出:queue: [a, b, c, d, e, f, g, h, l]a 剩余的元素:[b, c, d, e, f, g, h, l]b 剩余的元素:[c, d, e, f, g, h, l]c 剩余的元素:[d, e, f, g, h, l]d 剩余的元素:[e, f, g, h, l]e 剩余的元素:[f, g, h, l]f 剩余的元素:[g, h, l]g 剩余的元素:[h, l]h 剩余的元素:[l]l 剩余的元素:[][B, r, o, n, t, s, a, u, r, u, s]
面向抽象的思想写代码
LinkedList即实现了List接口,又实现了Queue接口,但是,在使用的时候,如果我们把它当作List,就获取List的引用,如果我们把它当作Queue,就获取Queue的引用:
// 这是一个List:List<String> list = new LinkedList<>();// 这是一个Queue:Queue<String> queue = new LinkedList<>();
