5.8. Creating a Priority Queue
Problem
You need to prioritize
objects: removing higher priority
objects from a Collection before lower priority
objects.
Solution
Use a
PriorityBuffer
to hold objects to be prioritized. Objects will be removed from this
Buffer according to a priority generated with a
Comparator. Whenever the remove( ) method is called on this Buffer
implementation, a PriorityBuffer uses the
Comparator to sort its contents, returning the
element of greatest priority. Using a
PriorityBuffer without a
Comparator causes the buffer to prioritize objects
by natural order, casting each object to
Comparable and comparing objects with the
compareTo( ) method; all objects must implement
the Comparable interface if no
Comparator is supplied. The following example
demonstrates the use of a PriorityBuffer without
supplying a
Comparator
:
import java.util.*;
import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.buffers.PriorityBuffer;
// Create a PriorityBuffer with no Comparator
Buffer priority = new PriortyBuffer( );
priority.add( new Long( 2 ) );
priority.add( new Long( 1 ) );
priority.add( new Long( 20 ) );
priority.add( new Long( 7 ) );
priority.add( new Long( 18 ) );
priority.add( new Long( 1 ) );
// Print the results in priority order
Iterator priorityIterator = priority.iterator( );
while( priorityIterator.hasNext( ) ) {
Long value = (Long) priority.next( );
System.out.prinltn( "Value: " + value );
}The previous example removes values from ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access