package rebelsky.exam2.solutions; import rebelsky.linear.Queue; /** * An implementation of queues using arrays. Currently incomplete. * * @author Samuel A. Rebelsky * @author Kevin Conor * @author CSC152 2004F * @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; if ((this.last == this.first) && (!this.isEmpty())) this.expand(); 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() private void expand() { // Allocate the new array Object[] newcontents = new Object[2*this.contents.length]; /* // Copy the elements incorrectly for (int i = 0; i < this.contents.length; i++) { newcontents[i] = contents[i]; } // for */ // Copy the elements for (int i = 0; i < this.contents.length; i++) { newcontents[i] = contents[this.first]; ++this.first; if (this.first == this.contents.length) this.first = 0; } // Update fields this.last = this.contents.length; this.contents = newcontents; this.first = 0; } // expand() public boolean isEmpty() { return this.contents[this.first] == null; } // isEmpty() } // class NewArrayBasedQueue