package rebelsky.linear; /** * An implementation of queues using arrays. Currently incomplete, * as it fails when the array fills. * * @author Samuel A. Rebelsky * @version 1.0 of October 2004. */ public class ArrayBasedQueue implements Queue { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** The index of the "last" thing. */ int last; /** The index of the "first" thing. */ int first; /** The stuff actually in the stack. */ Object[] contents; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ public ArrayBasedQueue() { this.last = -1; this.first = 0; this.contents = new Object[10]; } // ArrayBasedQueue() // +---------+------------------------------------------------- // | Methods | // +---------+ public void put(Object addMe) { this.last = this.last + 1; // Have we run out of space? If so, shift left. if (this.last == this.contents.length) { for (int i = this.first; i < this.contents.length; i++) { this.contents[i-this.first] = this.contents[i]; this.contents[i] = null; } // for this.last = this.last - this.first; this.first = 0; } // if this.contents[this.last] = addMe; } // put(Object) public Object get() throws Exception { if (this.contents[this.first] == null) throw new Exception("It's empty!"); Object returnMe = this.contents[this.first]; this.contents[this.first] = null; // Actually remove it. ++this.first; return returnMe; } // get() public Object peek() { return this.contents[this.first]; } // peek() public boolean isEmpty() { return this.contents[this.last] == null; } // isEmpty() } // class ArrayBasedQueue