Skip to main content
ICT
Lesson AB33 - PriorityQueues
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

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. void add(Object item)
    //Inserts item into the PriorityQueue.
    boolean isEmpty()
    //Returns true if the PriorityQueue has no //elements.
    Object peek()
    //Returns the next element without removing it.
    Object remove()
    //Returns and removes the next element according
    //to its given priority. The priority is
    //determined by the compareTo() method. Therefore
    //all elements added to the PriorityQueue must
    //implement the Comparable() interface. The
    //element with the lowest value in CompareTo()
    //will be returned.

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

    PriorityQueue <ClassName> myStack =
        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);
    }

    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.