/** * An array-based implementation of a Queue. * See QueueInft for documentation of functions defined in the interface * * @author gtowell * Created: Feb 10, 2020 * Modified: Oct 20, 2020 * @param */ public class ArrayQueue implements QueueInterface { /** 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 number of items in the queue */ private int count; /** The array location of the end of the queue (ie the * location of the item shown by the peek command */ private int frontLoc; public boolean offr(Q item) { if (count >= backingArray.length) return false; int rearLoc = (frontLoc + count) % backingArray.length; backingArray[rearLoc] = item; count++; return true; } /** * 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 */ @SuppressWarnings("unchecked") 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 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); } }