import java.util.NoSuchElementException; /** * An array-based implementation of a Queue. * See QueueInft for documentation of functions defined in the interface * * @author gtowell * Created: Feb 10, 2020 * @param */ public class ArrayQueue implements QueueIntf { /** the default capacity for the backing array */ private static final int CAPACITY = 40; /** The array in which the queue data is stored */ private Q[] backingArray; /** The array location of the head of the queue */ private int count; /** The array location of the end of the queue */ private int frontLoc; /** * Create an array backed queue with the default capacity. */ public ArrayQueue() { this(CAPACITY); } /** * Create an array backed queue with the given capacity * * @param qSize the capacity for the queue */ public ArrayQueue(int qSize) { count = 0; frontLoc = 0; backingArray = (Q[]) new Object[qSize]; } @Override public boolean isEmpty() { return count == 0; } @Override public int size() { return count; } @Override public boolean add(Q q) throws IllegalStateException { if (!offer(q)) throw new IllegalStateException("No space in Q"); return true; } @Override public Q remove() throws NoSuchElementException { Q q = poll(); if (q==null) throw new NoSuchElementException("The queue is empty"); return q; } @Override public Q element() throws NoSuchElementException { Q q = peek(); if (q==null) throw new NoSuchElementException("The queue is empty"); return q; } @Override public boolean offer(Q q) { if (count >= backingArray.length) return false; int loc = (frontLoc + count) % backingArray.length; backingArray[loc] = q; count++; return true; } @Override public Q poll() { if (isEmpty()) return null; Q rtn = backingArray[frontLoc]; backingArray[frontLoc] = null; count--; frontLoc = (frontLoc + 1) % backingArray.length; return rtn; } @Override public Q peek() { if (isEmpty()) return null; return backingArray[frontLoc]; } /** * Standard toString, show all eleents in queue. First * element is the item next from poll, last item in the * end of the queue */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("{ "); for (int i = 0; i < count; i++) { int loc = (frontLoc + i) % backingArray.length; sb.append(backingArray[loc] + " "); } sb.append("}"); return sb.toString(); } /** * Test that the queue operations do exactly what they * are supposed to do. * @param args */ public static void main(String[] args) { ArrayQueue aq = new ArrayQueue<>(3); System.out.println(aq.offer(5)); System.out.println(aq); System.out.println(aq.offer(7)); System.out.println(aq); System.out.println(aq.offer(9)); System.out.println(aq); System.out.println(aq.offer(4)); System.out.println(aq); System.out.println(aq.poll()); System.out.println(aq); System.out.println(aq.poll()); System.out.println(aq); System.out.println(aq.poll()); System.out.println(aq); System.out.println(aq.poll()); System.out.println(aq); } }