package rebelsky.exam2; import rebelsky.linear.Queue; /** * An implementation of queues using arrays. Currently incomplete. * * @author Samuel A. Rebelsky * @author Kevin Conor * @author YOUR NAME HERE * @version 1.01 of October 2004. */ public class NewArrayBasedQueue implements Queue { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** The index of the "last" thing. */ int last; /** The index of the "first" thing. */ int first; /** The stuff actually in the queue. */ Object[] contents; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ public NewArrayBasedQueue() { this.last = -1; this.first = 0; this.contents = new Object[3]; } // NewArrayBasedQueue() // +---------+------------------------------------------------- // | Methods | // +---------+ public void put(Object addMe) { this.last = this.last + 1; // Have we run off the end? If so, wrap around to // the beginning. if (this.last == this.contents.length) this.last = 0; this.contents[this.last] = addMe; } // put(Object) public Object get() throws Exception { // Note that the following line throws an exception // if the queue is empty. Hence, the remaining lines // will not be executed. Object returnMe = this.peek(); this.contents[this.first] = null; // Actually remove it. ++this.first; if (this.first == this.contents.length) this.first = 0; return returnMe; } // get() public Object peek() throws Exception { if (this.contents[this.first] == null) throw new Exception("It's empty!"); return this.contents[this.first]; } // peek() public boolean isEmpty() { return this.contents[this.first] == null; } // isEmpty() } // class NewArrayBasedQueue