Skip to main content
ICT
Lesson AB33 - PriorityQueues
 
Main   Previous Next
 

E. The PriorityQueue Class page 7 of 9

  1. The AP subset requires students to know the following methods of the java.util.PriorityQueue:
  2. // Inserts item into the PriorityQueue.
    void add(Object item)

    // Returns true if the PriorityQueue has no elements.
    boolean isEmpty()

    // Returns the next element without removing it.
    Object peek()

    // Returns and removes the next element according to its
    // given priority. The priority is determined by the
    // compareTo() method. Therefore all elements added to
    // tthe PriorityQueue must implement the Comparable()
    // interface.The element with the lowest value in CompareTo()
    // will be returned.

    Object remove()

  3. To declare a reference variable for a PriorityQueue, do the following.

    PriorityQueue<ClassName> pq = new PriorityQueue<ClassName>();

  4. Here is a short example showing how to create, populate, and deconstruct a PriorityQueue.

    PriorityQueue<Integer> q = new PriorityQueue<Integer>();

    for( int i = 5; i >= 1; i-- )
    {
       q.add( i );
    }

    for(Integer temp : q)
    {
       System.out.println( temp );
    }

    System.out.println();

    while( !q.isEmpty() )
    {
       System.out.println( q.remove() );
    }

    Output:

    1
    2
    3
    4
    5

    1
    2
    3
    4
    5

    In this example, the output prints from one to five twice. This is because the PriorityQueue will insert the elements it receives in the order of their priority rather than the order that they are received. Note: The Integer class implements Comparable.

 

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.