Java集合源码学习(13)_Queue接口以及基础实现AbstractQueue

时间:2021-03-25 17:53:59

1:Queue接口

继承接口Collection;

通常而言,顺序是FIFO,例外是优先级队列(顺序由指定的Comparator来决定)和栈(LIFO)
增加了下面几个方法:

  Throws exception Returns special value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()

2:AbstractQueue

add()、remove()、element()是基于offer()、poll()、peek()来实现的; 代码如下:
public abstract class AbstractQueue<E> extends AbstractCollection<E> implements Queue<E> {
protected AbstractQueue() {
}
public boolean add(E e) {
if (offer(e))
return true;
else
throw new IllegalStateException("Queue full");
}
public E remove() {
E x = poll();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
public E element() {
E x = peek();
if (x != null)
return x;
else
throw new NoSuchElementException();
}
public void clear() {
while (poll() != null)
;
}
public boolean addAll(Collection<? extends E> c) {
if (c == null)
throw new NullPointerException();
if (c == this)
throw new IllegalArgumentException();
boolean modified = false;
Iterator<? extends E> e = c.iterator();
while (e.hasNext()) {
if (add(e.next()))
modified = true;
}
return modified;
}

}