Queue remove/poll, add/offer, element/peek整理

Queue remove/poll, add/offer, element/peek整理

offer/add

  • 相关add方法
对于AbstractQueue等实现为:
public boolean add(E e) {
        if (offer(e))
            return true;
        else
            throw new IllegalStateException("Queue full");
}
而对于大多数实现为:或者直接调用offer操作
public boolean add(E e) {
        linkLast(e);
        return true;
}
void linkLast(E e) {
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
 }

官方对于add方法的描述是:

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning {@code true} upon success and throwing an {@code IllegalStateException} if no space is currently available
即:如果容量允许会立即插入指定元素到队列并返回success,如果没有足够的容量,会抛出异常

 

  • 相关offer方法:
public boolean offer(E e) {
        return add(e);
}

官方对于offer方法的描述是:

Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions. When using a capacity-restricted queue, this method is generally
 preferable to {@link #add}, which can fail to insert an element only by throwing an exception.
  即:在没有容量限制尽可能快的插入指定元素到队列,当使用一个容量限制的队列,这个方法一般是优于add方法,后者(即add)在插入元素失败会引发异常
  • 总结

对于有队列大小限制,如果队列在满队列的情况下,这时候add方法会执行失败,抛出异常,这时候如果offer操作,则只会返回false

remove/poll

  • 相关poll

官方解读:

Retrieves and removes the head of this queue, or returns {@code null} if this queue is empty.
  • 相关remove

官方解读:

Retrieves and removes the head of this queue.  This method differs from {@link #poll poll} only in that it throws an exception if this queue is empty.
  • 总结

这两个方法对比很明显,都是查询并移除队列的头元素,不同的是如果队列为empty,remove会抛出异常,poll则会返回null

element/peek

  • element:
Retrieves, but does not remove, the head of this queue, or returns {@code null} if this queue is empty.
  • peek:
Retrieves, but does not remove, the head of this queue.  This method differs from {@link #peek peek} only in that it throws an exception if this queue is empty.
  • 总结

它俩功能是查询队列头部元素但不移除元素,与之前的remove/poll一样,element/peek也是诸如此类的区别,在队列为empty时,element会抛出一个异常,而peek会返回null.

对于queue的几个容易混淆的方法整理就到这

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值