Queue
对列是一个先进先出的容器,即从容器的一端放入事物,从另一端取出来并且事物放入容器的顺序与取出的顺序是相同的,队列常被当做一种可靠的将对象从程序的某个区域传输到另一个区域的途径。
LinkedList可以用作Queue的一种实现,可以将LinkedList向上转型为Queue。
Queue接口窄化了对LinkedList的方法的访问权限,以使得只有恰当的方法才可使用。
使用LinkedList向上转型构造一个Queue
import java.util.*;
public class QueueDemo {
public static void printQ(Queue queue) {
while(queue.peek() != null)
System.out.print(queue.remove() + " ");
System.out.println();
}
public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<Integer>();
Random rand = new Random(47);
for(int i = 0; i < 10; i++)
queue.offer(rand.nextInt(i + 10));
printQ(queue);
Queue<Character> qc = new LinkedList<Character>();
for(char c : "Brontosaurus".toCharArray())
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
*///:~
PriorityQueue
先进先出描述了最典型的对列规则。对列规则是指定在给定一组对列中的元素的情况下,确定下一个弹出对列的元素的规则。先进先出是声明的下一个元素应该等待的最长的元素。
当使用PriorityQueue上调用offer()方法来插入一个对象时,这个对象会在对列中被排序。默认的排揎将使用对象在对列中的自然排序、PriorityQueue可以确保当你调用peek(),poll()和remove()方法时,获取的元素将是对列中优先级最高的元素。