100个Java工具类之61:队列类Queue

Queue类,队列,是一种数据结构,遵循先进先出的原则。

下面通过实例能更好地理解Queue。

一、添加元素

add和offer方法都是添加元素。区别是offer添加元素时候,如果队列已满,会返回false,而

add方法会抛出IllegalStateException异常

Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
输出:[1, 2]

二、移除并返回队头元素

remove和poll方法都是移除头部元素。区别是poll方法在队列为空时返回null,而remove在队列为空时会抛出NoSuchElementException异常。

Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
int remove = queue.remove();
输出:1

三、获取队头元素

Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
int peek = queue.peek();
输出:1

四、队列判空

Queue<Integer> queue = new LinkedList<>();
boolean isEmpty = queue.isEmpty();
输出:true

 

五、遍历队列

Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
Iterator<Integer> iterator = queue.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
输出:1 2

六、检查是否包含某元素

queue.contains(11);
输出:false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值