码迷,mamicode.com
首页 > 编程语言 > 详细

Java-- Queue

时间:2014-06-28 15:42:36      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:style   blog   java   color   使用   os   

队列相信大家也很熟悉,我就不说了。

本文采用LinkedList提供的方法以支持队列的行为,并且它实现了Queue的接口,因此LinkedList可以作为Queue的一种实现。通过将LinkedList向上转型为Queue,下面的示例使用了在Queue接口中与Queue相关的方法:

 1 package com.holding;
 2 
 3 import java.util.*;
 4 
 5 public class QueueDemo {
 6     public static void printQ(Queue queue){
 7         while(queue.peek() != null)
 8             System.out.print(queue.remove()+" ");
 9         System.out.println();
10     }
11     
12     public static void main(String[] args){
13         Queue<Integer> queue = new LinkedList<Integer>();
14         Random rand = new Random(47);
15         for(int i=0;i<10;i++)
16             queue.offer(rand.nextInt(i+10));
17         printQ(queue);
18         Queue<Character> qc = new LinkedList<Character>();
19         for(char c:"Brontosaurus".toCharArray())
20             qc.offer(c);
21         printQ(qc);
22     }
23 }

结果如下:

 1 8 1 1 1 5 14 3 1 0 1

2 B r o n t o s a u r u s  

offer()方法是Queue相关的方法之一,它在允许的情况下,将一个元素插入到队尾,或者返回false.peek()和element()都将在不移除的情况下返回队头,但是peek()方法在队列为空时返回null.而element()会抛出NoSuchElementException异常。

  自动包装机制会自动的将nextInt()方法的int结果转化为Queue所需要的Integer对象,将char c 转换为qc所需要的Character对象。

Java-- Queue,布布扣,bubuko.com

Java-- Queue

标签:style   blog   java   color   使用   os   

原文地址:http://www.cnblogs.com/fxyfirst/p/3798009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!