java Queue(队列)

  队列是一个典型的先进先出的容器。即从容器的一端放入事物,从另一端取出,并且事物放入容器的顺序与取出的顺序是相同的。队列常被当作一种可靠的将对象从程序的某个区域传输到另一个区域的途径。队列在并发编程中特别重要,因为它们可以安全地将对象从一个任务传输给另一个任务。

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

import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;


public class QueueDemo {
    public static void printQueue(Queue queue){
        while (queue.peek()!=null) {  //queue.peek 检索,但不删除该队列的头部,如果该队列为空,则返回null。
        System.out.print(queue.remove()+" "); //检索并删除该队列的头部。把头部的值打印出来
        }
    }
    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<Integer>(); //将LinkedList向上转型为Queue对象,queue的持有对象是Integer类型的
        Random rand = new Random(47); //随机数
        for (int i = 0; i < 10; i++) {
            queue.offer(rand.nextInt(i+10)); //把随机到的数插入队列中去。
        }
        printQueue(queue); //打印队列中的元素
        System.out.println();//换行
        Queue<Character> qc = new LinkedList<Character>();//将LinkedList向上转型为Queue对象,queue的持有对象是Character类型的
        for (Character character : "Brontosaurus".toCharArray()) {//把字符串转成字符数组 
            qc.offer(character); //把遍历的字符插入到队列中
        }
        printQueue(qc);//打印队列中的字符
    }
}
上面这段代码的输出结果为:

8 1 1 1 5 14 3 1 0 1 
B r o n t o s a u r u s 

对执行几次这段代码其输出结果依然是这两串。不明白为什么总是随机到这些数字的可以看看下面这篇文章:https://blog.csdn.net/zhang41228/article/details/77069734

下一篇给大家普及一下栈的基础!!!

猜你喜欢

转载自blog.csdn.net/qq_40207976/article/details/82415178
今日推荐