/** * 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 * Modified: April 12, 2021 */ public class PriorityQSAL, 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 PriorityQSAL() { 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) { PriorityQSAL pq = new PriorityQSAL<>(); pq.offer(1, "flopsy"); pq.offer(10, "mopsy"); pq.offer(5, "peter"); System.out.println(pq.poll()); System.out.println(pq.poll()); System.out.println(pq.poll()); System.out.println(); PriorityQSAL pqpq = new PriorityQSAL<>(); pqpq.offer(2,"Jane"); pqpq.offer(1,"WET"); pqpq.offer(5, "WAS"); System.out.println(pqpq.poll()); System.out.println(pqpq.poll()); System.out.println(pqpq.poll()); } }