JAVA集合源码攻坚战(18)——AbstractQueue
前言
今天周一,刚上班,先看看源码,补充下能量!
正文
AbstractQueue的地位
java.util
Class AbstractQueue<E>
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractQueue<E>
参数类型
E - 在此集合中保存的元素的类型
All Implemented Interfaces:
Iterable <E>, Collection <E>, Queue <E>
已知直接子类:
ArrayBlockingQueue , ConcurrentLinkedQueue , DelayQueue , LinkedBlockingDeque , LinkedBlockingQueue , LinkedTransferQueue , PriorityBlockingQueue , PriorityQueue , SynchronousQueue
可以看到,AbstractQueue继承了AbstractCollection类,实现了Queue。
AbstractQueue是提供了对Queue的一些操作的骨架实现。
在官方文档中,特别提到了一点
A Queue implementation that extends this class must
minimally define a method {@link Queue#offer} which does not permit
insertion of null elements, along with methods {@link
Queue#peek}, {@link Queue#poll}, {@link Collection#size}, and
{@link Collection#iterator}. Typically, additional methods will be
overridden as well. If these requirements cannot be met, consider
instead subclassing {@link AbstractCollection}.
意思就是
一个继承了该类的Queue的实现类,必须最低限度的定义一个不允许插入null元素的offer方法。如果无法满足这些要求,请考虑使用AbstractCollection。
构造方法
/**
* 供子类使用的构造器
* Constructor for use by subclasses.
*/
protected AbstractQueue() {
}
数据操作方法
1、添加操作
public boolean add(E e) {
// 依赖于Queue接口中的offer方法
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
2、移除操作
public E remove() {
// 实际调用Queue中的poll方法
E x = poll();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
3、获取操作
public E element() {
// 实际调用Queue的peek方法
E x = peek();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
4、清空操作
public void clear() {
// 循环调用poll方法,直到poll方法返回null,表示队列为空
while (poll() != null)
;
}
5、批量添加操作
public boolean addAll(Collection<? extends E> c) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}