Queue接口继承自Collection接口,java.util.Queue,队列也可以保存一组元素但是存取元素必须遵循先进先出模式。
1、常用实现类:LinkedList
offer方法:入队操作,向队列末尾追加元素(返回值boolean类型:添加是否成功)poll方法 :出队操作,获取队首元素后该元素即从队列中被删除(返回值:元素类型,返回被出队的元素)peek方法: 引用队首元素,元素不做出队操作(返回值:元素类型:返回队首元素)
import java.util.LinkedList;
import java.util.Queue;
public class QueueDemo {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
//队尾添加元素
queue.offer("one");
queue.offer("two");
queue.offer("three");
System.out.println(queue); //[one, two, three]
//出队队首元素
String str = queue.poll();
System.out.println(str); //one
System.out.println(queue); //[two, three]
//返回队首元素
String res = queue.peek();
System.out.println(res); //two
System.out.println(queue); //[two, three]
}
}
2、遍历队列:
1)使用poll方法遍历队列:
while(queue.size()>0){
String s = queue.poll();
System.out.println(s);
}
System.out.println(queue);
这种方法可以实现队列的遍历,但是元素遍历之后,queue会清空。
2)使用迭代器遍历队列:元素不会因此被队列删除
for(String s : queue){
Sustem.out.println(s);
}
System.out.println(queue);
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。