队列是一个典型的先进先出(FIFO)的容器。即从容器的一段放入事物,从另一端取出,并且事物放入容器的顺序与取出的顺序是相同的。
LinkedList实现了Queue接口,因此LinkedList可用作Queue的一种实现。Queue接口限制了LinkedList里的一些方法,只有队列所需的方法才允许被使用(接口的作用嘛)。
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class QueueTest {
public static void main(String[] args){
Queue<Integer> integers = new LinkedList<Integer>();
Queue<Character> characters = new LinkedList<Character>();
Random rand = new Random();
for (int i = 0; i < 10; i++) {
integers.offer(rand.nextInt(100));
}
while (integers.peek()!=null) System.out.print(integers.poll());
System.out.println();
for (char c : "No Country for Old Men".toCharArray()) {
characters.offer(c);
}
while (characters.peek()!=null) System.out.print(characters.poll()+" ");
}
}
//173198386858439895
//N o C o u n t r y f o r O l d M e n
PriorityQueue<>
优先级队列声明下一个弹出的元素为优先级最高的元素。
方法iterator() 中提供的迭代器不 保证以任何特定的顺序遍历优先级队列中的元素。
import java.util.PriorityQueue;
import java.util.Random;
public class PriorityQueueTest {
public static void main(String[] args){
Random rand = new Random();
PriorityQueue<Integer> queue = new PriorityQueue<Integer>();
for (int i = 0; i < 10; i++) {
queue.offer(rand.nextInt(1000));
}
for (int i : queue) {
System.out.print(i+" ");
}
}
}
// 292 457 395 563 526 624 639 603 804 852