1、java中的Queue有点特殊,它的实现是由LinkedList完成的。
下面通过分析一个《Thinking in Java》中的代码来了解Queue的实现。
import java.util.*;
public class QueueDemo {
public static void printQ(Queue queue) {
while(queue.peek() != null)//peek()方法返回队首元素,但不删除该元素。属于返回逻辑值的方法类型。
System.out.print(queue.remove() + " ");//remove()方法从队首移除一个元素。属于抛出异常的方法类型。
System.out.println();
}
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<Integer>();//创建一个Queue<Integer>,注意用LinkedList实现。
Random rand = new Random(47);
for(int i = 0; i < 10; i++)
queue.offer(rand.nextInt(i + 10));//offer(e)方法向队列中加入元素。属于返回逻辑值的方法类型。
printQ(queue);
Queue<Character> qc = new LinkedList<Character>();
for(char c : "Brontosaurus".toCharArray())//foreach方法
qc.offer(c);
printQ(qc);
}
} /* Output:
8 1 1 1 5 14 3 1 0 1
B r o n t o s a u r u s
*/
接下来解释一下注释中的几点
①对于实现队列的同一种操作,Queue中都定义了两种返回方式的方法(a抛出异常b返回特定值)
向队列中加入元素:a、add() b、 offer()
返回队首元素,但不删除该元素:a、elelment(), b、peek()
从队首移除一个元素:a、remove(), b、poll()
②Queue使用LinkedList实现是因为Linkedlist实现了Queue接口。这还是一种上转型,LinkedList上转型为Queue类型。