zoukankan      html  css  js  c++  java
  • java Queue

    队列是一个典型的先进先出(FIFO)的容器,即从容器的一端放入事物,从另一端取出,并且事物放入容器的顺序与取出的顺序是相同的,队列常常被当作一种可靠的对象从程序的某个区域传输到另一个区域,队列在并发编程中特别重要

    package java.util;
    
    public interface Queue<E> extends Collection<E> {   
        boolean add(E e);    
        boolean offer(E e);//在允许的情况下,将元素element插入队尾 ,或者放回false   
        E remove();//移除并返回队头,在队列为空时throw NoSuchElementException
        E poll();  //移除并返回队头,在队列为空时返回null
        E element();//在不移除的情况下,返回队头,在队列为空时throw NoSuchElementException
        E peek(); //在不移除的情况下,返回队头,在队列为空时返回null
    }

    对于Queue所继承的Collection在不需要使用其它任何方法的情况下,就可以拥有一个可用的Queue

    通用的有:LinkedList

    //Linked提供了方法以支持队列的行为,并且它实现了Queue接口,因此Linked可以用作Queue的一种实现
    //通过向上转型为Queue,本例使用了在Queue接口中与Queue有关的办法
    package object;
    import java.util.*;
    
    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>();
        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(char c : "Brontosaurus".toCharArray())
          qc.offer(c);
        printQ(qc);
      }
    } /* Output:
    8 1 1 1 5 14 3 1 0 1
    B r o n t o s a u r u s
    *///:~
  • 相关阅读:
    P1744 采购特价商品
    P1359 租用游艇
    P3092 [USACO13NOV]没有找零No Change
    P1272 重建道路
    P2014 选课
    P1026 统计单词个数
    P1776 宝物筛选_NOI导刊2010提高(02)
    自定义异步非阻塞tornado框架
    tornado进阶篇
    tornado基础篇
  • 原文地址:https://www.cnblogs.com/jiangfeilong/p/10283987.html
Copyright © 2011-2022 走看看