泛型与容器(4)——Queue

    队列在并发编程中特别重要,它们可以安全地将对象从一个任务传输给另一个任务。
    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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值