001package horstmann.ch03_queue;
002/**
003    A first-in, first-out bounded collection of messages.
004 */
005public class MessageQueue
006{
007        /**
008       Constructs an empty message queue.
009       @param capacity the maximum capacity of the queue
010       <p><b>Precondition:</b> capacity > 0
011         */
012        public MessageQueue(int capacity)
013        {
014                elements = new Message[capacity];
015                count = 0;
016                head = 0;
017                tail = 0;
018        }
019
020        /**
021       Remove message at head.
022       @return the message that has been removed from the queue
023       <p><b>Precondition:</b> size() > 0
024         */
025        public Message remove()
026        {
027                Message r = elements[head];
028                head = (head + 1) % elements.length;
029                count--;
030                return r;
031        }
032
033        /**
034       Append a message at tail.
035       @param aMessage the message to be appended
036       <p><b>Precondition:</b> !isFull();
037         */
038        public void add(Message aMessage)
039        {
040                elements[tail] = aMessage;
041                tail = (tail + 1) % elements.length;
042                count++;
043        }
044
045        /**
046       Get the total number of messages in the queue.
047       @return the total number of messages in the queue
048         */
049        public int size()
050        {
051                return count;
052        }
053
054        /**
055       Checks whether this queue is full
056       @return true if the queue is full
057         */
058        public boolean isFull()
059        {
060                return count == elements.length;
061        }
062
063        /**
064       Get message at head.
065       @return the message that is at the head of the queue
066       <p><b>Precondition:</b> size() > 0
067         */
068        public Message peek()
069        {
070                return elements[head];
071        }
072
073        private Message[] elements;
074        private int head;
075        private int tail;
076        private int count;
077}