Source of BoundedQueue.java


  1: import java.util.*;

  3: /**
  4:     A first-in, first-out bounded collection of objects.
  5: */
  6: public class BoundedQueue<E> extends AbstractCollection<E>
  7: {
  8:    /**
  9:        Constructs an empty queue.
 10:        @param capacity the maximum capacity of the queue
 11:        @precondition capacity > 0
 12:    */
 13:    public BoundedQueue(int capacity)
 14:    {
 15:       elements = new Object[capacity];
 16:       count = 0;
 17:       head = 0;
 18:       tail = 0;
 19:    }

 21:    public Iterator<E> iterator()
 22:    {
 23:       return new
 24:          Iterator<E>()
 25:          {
 26:             public boolean hasNext()
 27:             {
 28:                return visited < count;
 29:             }

 31:             public E next()
 32:             {
 33:                int index = (head + visited) % elements.length;
 34:                E r = (E) elements[index];
 35:                visited++;
 36:                return r;
 37:             }

 39:             public void remove()
 40:             {
 41:                throw new UnsupportedOperationException();
 42:             }

 44:             private int visited = 0;
 45:          };
 46:    }

 48:    /**
 49:        Remove object at head.
 50:        @return the object that has been removed from the queue
 51:        @precondition size() > 0
 52:    */
 53:    public E remove()
 54:    {
 55:       E r = (E) elements[head];
 56:       head = (head + 1) % elements.length;
 57:       count--;
 58:       return r;
 59:    }

 61:    /**
 62:        Append an object at tail.
 63:        @param anObject the object to be appended
 64:        @return true since this operation modifies the queue.
 65:        (This is a requirement of the collections framework.)
 66:        @precondition !isFull()
 67:    */
 68:    public boolean add(E anObject)
 69:    {
 70:       elements[tail] = anObject;
 71:       tail = (tail + 1) % elements.length;
 72:       count++;
 73:       return true;
 74:    }

 76:    public int size()
 77:    {
 78:       return count;
 79:    }

 81:    /**
 82:        Checks whether this queue is full.
 83:        @return true if the queue is full
 84:    */
 85:    public boolean isFull()
 86:    {
 87:       return count == elements.length;
 88:    }

 90:    /**
 91:        Gets object at head.
 92:        @return the object that is at the head of the queue
 93:        @precondition size() > 0
 94:    */
 95:    public E peek()
 96:    {
 97:       return (E) elements[head];
 98:    }

100:    private Object[] elements;
101:    private int head;
102:    private int tail;
103:    private int count;
104: }