泛型与容器(4)——Queue

来源:互联网 发布:u盘芯片检测软件 编辑:程序博客网 时间:2024/05/29 11:24
    队列在并发编程中特别重要,它们可以安全地将对象从一个任务传输给另一个任务。
    LinkedList提供了方法以支持队列的行为,并且它实现了Queue接口,通过将LinkedList上转型为Queue。
示例:

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>();// 将LinkedList上转型为Queue// 随机数队列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 (Character c : "Browser".toCharArray()) {qc.offer(c);}printQ(qc);}}

运行结果:

8 1 1 1 5 14 3 1 0 1 B r o w s e r


PriorityQueue优先级队列
    优先级队列声明下一个弹出元素是最需要的元素(具有最高的优先级)。
示例:

public class PriorityQueueDemo {public static void main(String[] args) {// 随机数队列PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();Random rand = new Random(47);for (int i = 0; i < 10; i++) {priorityQueue.offer(rand.nextInt(i + 10));}QueueDemo.printQ(priorityQueue);// 增加一个数组后的队列List<Integer> ints = Arrays.asList(25, 22, 20, 18, 14, 9, 3, 1, 1, 2,3, 9, 14, 18, 21, 23, 25);priorityQueue = new PriorityQueue<Integer>(ints);QueueDemo.printQ(priorityQueue);// reverseOrder()反序排列后的队列priorityQueue = new PriorityQueue<Integer>(ints.size(),Collections.reverseOrder());priorityQueue.addAll(ints);QueueDemo.printQ(priorityQueue);// 字符串队列String fact = "HELLO NIN HAO MA YOU SHOULD BE SMARTER";List<String> strings = Arrays.asList(fact.split(" "));PriorityQueue<String> stringPQ = new PriorityQueue<String>(strings);QueueDemo.printQ(priorityQueue);// 字符串反序队列stringPQ = new PriorityQueue<String>(stringPQ.size(),Collections.reverseOrder());stringPQ.addAll(strings);QueueDemo.printQ(stringPQ);// 字符队列Set<Character> charSet = new HashSet<Character>();for (char c : fact.toCharArray())charSet.add(c);PriorityQueue<Character> characterPQ = new PriorityQueue<Character>(charSet);QueueDemo.printQ(characterPQ);}}

运行结果:

0 1 1 1 1 1 3 5 8 14 1 1 2 3 3 9 9 14 14 18 18 20 21 22 23 25 25 25 25 23 22 21 20 18 18 14 14 9 9 3 3 2 1 1 YOU SMARTER SHOULD NIN MA HELLO HAO BE A B D E H I L M N O R S T U Y



0 0