运行结果: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
运行结果: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
本文介绍队列在并发编程中的作用及其实现方式,通过具体示例展示了如何利用LinkedList实现队列行为,并介绍了优先级队列的概念及其在不同场景中的应用。
740

被折叠的 条评论
为什么被折叠?



