/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain. Use, modify, and * redistribute this code in any way without acknowledgement. */ package java.util; /** * This class provides skeletal implementations of some {@link Queue} * operations. The implementations in this class are appropriate when * the base implementation does not allow null * elements. Methods {@link #add add}, {@link #remove remove}, and * {@link #element element} are based on {@link #offer offer}, {@link * #poll poll}, and {@link #peek peek}, respectively but throw * exceptions instead of indicating failure via false or * null returns. * *

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 a * {@link Collection#iterator} supporting {@link * Iterator#remove}. Typically, additional methods will be overriden * as well. If these requirements cannot be met, consider instead * subclassing {@link AbstractCollection}. * * @since 1.5 * @author Doug Lea */ public abstract class AbstractQueue extends AbstractCollection implements Queue { /** * Constructor for use by subclasses. */ protected AbstractQueue() { } /** * Adds the specified element to this queue. This implementation * returns true if offer succeeds, else * throws an IllegalStateException. * th * @param o the element * @return true (as per the general contract of * Collection.add). * * @throws NullPointerException if the specified element is null * @throws IllegalStateException if element cannot be added */ public boolean add(E o) { if (offer(o)) return true; else throw new IllegalStateException("Queue full"); } /** * Retrieves and removes the head of this queue. * This implementation returns the result of poll * unless the queue is empty. * * @return the head of this queue. * @throws NoSuchElementException if this queue is empty. */ public E remove() { E x = poll(); if (x != null) return x; else throw new NoSuchElementException(); } /** * Retrieves, but does not remove, the head of this queue. * This implementation returns the result of peek * unless the queue is empty. * * @return the head of this queue. * @throws NoSuchElementException if this queue is empty. */ public E element() { E x = peek(); if (x != null) return x; else throw new NoSuchElementException(); } /** * Removes all of the elements from this collection. * The collection will be empty after this call returns. *

This implementation repeatedly invokes {@link #poll poll} until it * returns null. */ public void clear() { while (poll() != null) ; } }