LinkedList提供了方法支持队列的行为,并且它实现了Queue接口,因此LinkedList可以用作Queue的一种实现。
package cn.usst.queue.demo;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
/*
* Queue的基本使用
*/
public class QueueDemo {
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<Integer>();
Random random = new Random(47);
for(int i=0; i<10; i++){
queue.offer(random.nextInt(i+10));
}
printQ(queue);
Queue<Character> qc = new LinkedList<Character>();
for(char c : "Brontosaurus".toCharArray()){
qc.offer(c);
}
printQ(qc);
}
private static void printQ(Queue queue) {
while(queue.peek() !=null ){
System.out.println(queue.remove() + " ");
}
System.out.println();
}
}
/*
* Offer()将一个元素插入到队尾
* peek()和element()都是在移除的情况下返回队头
* peek()方法在队列为空时返回null,element()会抛出NoSuchElementException异常
* poll()和remove()方法将移除并返回队头
* poll()在队列为空时返回null,而remove()会抛出NoSuchElementException异常
*/
PriorityQueue:优先队列的实现
package cn.usst.queue.demo;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
public class PriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();
Random rand = new Random();
for(int i=0; i<10; i++){
priorityQueue.offer(rand.nextInt(i+10));
}
printQ(priorityQueue);
List<Integer> ints = Arrays.asList(25, 22, 20, 18, 14, 9, 8, 2, 4, 7);
priorityQueue = new PriorityQueue<Integer>(ints);
printQ(priorityQueue);
//反向输出
priorityQueue = new PriorityQueue<Integer>(ints.size(), Collections.reverseOrder());
priorityQueue.addAll(ints);
printQ(priorityQueue);
}
private static void printQ(Queue queue) {
while(queue.peek() !=null ){
System.out.println(queue.remove() + " ");
}
System.out.println();
}
}