概念
java.util.Queue
集合是Collection
集合的子集合,与List
集合属于平级关系。Queue
集合的主要描述先进先出=特征=的数据结构,叫做队列(first in first out FIFO
)。- 该集合的主要实现类是LinkedList类,因为该类在增删方面比较有优势。
常用的方法
方法声明 | 功能介绍 |
---|---|
boolean offer(E e) |
元素放入队列中,添加成功返回true |
E poll() |
出队元素,队首删除并返回删除的元素 |
E peek() |
队列首位元素 不删除 |
案例题目
准备一个Queue集合,将数据11、22、33、44、55依次入队并打印,
然后查看队首元素并打印,然后将队列中所有数据依次出队并打印。
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
public static void main(String[] args) {
//1.
Queue queue = new LinkedList();
//2.元素放入队列中
for (int i = 1; i < 6; i++) {
boolean offer = queue.offer(i * 11);
System.out.println("queue队列中元素有:" + queue);
}
//3.查看队列首位元素
System.out.println("队列首位元素:"+ queue.peek());//11
//4.队列数据出队
int len = queue.size();
for (int i = 1; i <= len; i++) {
System.out.println("出队元素:"+ queue.poll());
}
//5,队列中元素
System.out.println(queue);//[]
}
}