队列是一个典型的先进先出的容器,即容器的一端放入事物,从另一端取出,且事物存入和取出是相同的,队列常被当作一种可靠的将对象从程序的某个区域传输到另一个区域的途径。基于此,队列在并发编程中特别重要。
LinkedList提供了方法以支持队列的行为,且实现了Queue接口,因此ListedList可以用作Queue的一种实现。示例:
package com.record;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
public class QueueDemo
{
public static void printQ(Queue queue)
{
while(queue.peek()!=null)
{
System.out.println(queue.remove()+" ");
}
System.out.println();
}
public static void main(String[] args)
{
Queue<Integer> queue = new LinkedList<Integer>();
Random random = new Random(47);
for(int i=0;i<10;i++)
queue.offer(random.nextInt(i+10));
printQ(queue);
Queue< Character> qc = new LinkedList<Character>();
for(char c:"Brontosaurus".toCharArray())
qc.offer(c);
printQ(qc);
}
}
offer方法在允许的情况下,将一个元素插入到队尾,或返回false,peek和element都将在不移除的情况下返回队头,但是peek方法在队列为空时返回null,而element会抛出NoSuchElementException异常,poll和remove方法将移除并返回对头,poll在队列为空时返回null,remove会抛出NoSuchElementException异常。