天天看點

Java集合源碼學習(13)_Queue接口以及基礎實作AbstractQueue

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;
	}

}