zoukankan      html  css  js  c++  java
  • Java Queue

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

    本文采用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对象。

  • 相关阅读:
    桥接,NAT,Host Only的区别
    PHP并发IO编程之路
    Git SSH Key 生成步骤
    composer安装学习
    db file sequential read等待事件的一点研究
    多个hints 怎么写?
    再次遭遇笛卡尔积
    pl/sql 在一个程序块里打印日志输出到表格
    pl/sql 程序块里打印问题
    利用ordered hints优化SQL
  • 原文地址:https://www.cnblogs.com/fxyfirst/p/3798009.html
Copyright © 2011-2022 走看看