/** * Implements PriorityQueue2 using an unsorted ArrayList */ import java.util.*; public class PQ2ArrayList { private ArrayList list; private Comparator c; public PQ2ArrayList(Comparator c) { this.list = new ArrayList(); this.c = c; } /** * Returns the number of items in the queue. */ public int size() { return this.list.size(); } /** * Adds a new item to the priority queue. * @param item the item to add */ public void add(T item) { this.list.add( item ); } /** * Removes the item with highest priority from the queue. * @return */ public T remove() { if (size() == 0) return null; T biggestSoFar = list.get(0); for (T item: list) { if (c.compare( biggestSoFar, item ) < 0) { biggestSoFar = item; } } this.list.remove( biggestSoFar ); return biggestSoFar; } public static void main( String[] args ) { PQ2ArrayList pq = new PQ2ArrayList(new IntComparator()); pq.add( 5 ); pq.add( 10 ); pq.add( 1 ); System.out.println( "removing " + pq.remove() ); System.out.println( "size is now " + pq.size() ); } } // for testing purposes!!! class IntComparator implements Comparator { public IntComparator() {;} public int compare(Integer o1, Integer o2) { return o1-o2; } }