/** * A priority queue. This priority Queue is built on top of a sorted ArrayList class * * @param the Key element. This must implement Comparable. * @param The Value element. This could be anything. * * For methods that exactly follow the interface, see the documentation in the interface. * * @author gtowell * Created APRIL 6, 2020 * Modified: Oct 18, 2020 */ public class PriorityQueueSAL, V> extends AbstractPriorityQueue { /** The thing actually holding the data in the priority queue. Using an ArrayList * to get unbounded length. */ final private SAL> pqStore; /** * Initialize the priority queue */ public PriorityQueueSAL() { this(Ordering.ASCENDING); } public PriorityQueueSAL(Ordering order) { this.order=order; pqStore = new SAL<>(SAL.Ordering.DESCENDING); } @Override public int size() { return pqStore.size(); } @Override public boolean isEmpty() { return pqStore.isEmpty(); } @Override public boolean offer(K newK, V newV) { Pair entry = new Pair<>(newK, newV); pqStore.add(entry); // Note that this always succeeds, so always return true. return true; } @Override public V poll() { if (isEmpty()) return null; Pair p = pqStore.getAndRemove(pqStore.size()-1); return p.theV; } @Override public V peek() { Pair entry = pqStore.get(pqStore.size()-1); if (entry==null) return null; return entry.theV; } public String toString() { return pqStore.toString(); } public static void main(String[] args) { PriorityQueueSAL pq = new PriorityQueueSAL<>(Ordering.ASCENDING); pq.offer(1, new Rabbit(Rabbit.BreedEnum.DwarfDutch, 1, "flopsy")); pq.offer(10, new Rabbit(Rabbit.BreedEnum.DwarfDutch, 10, "mopsy")); pq.offer(5, new Rabbit(Rabbit.BreedEnum.DwarfDutch, 5, "peter")); System.out.println(pq.poll()); System.out.println(pq.poll()); System.out.println(pq.poll()); System.out.println(); PriorityQueueSAL pqpq = new PriorityQueueSAL<>(Ordering.DESCENDING); pqpq.offer(1,"Jane"); pqpq.offer(10,"WET"); pqpq.offer(5, "WAS"); System.out.println(pqpq.poll()); System.out.println(pqpq.poll()); System.out.println(pqpq.poll()); } }