Skip to main content
ICT
Lesson AB31 - Stacks and Queues
 
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 >  
 

D. The Java Queue Interface page 6 of 10

  1. The AP subset requires students to know the following methods of the java.util.Queue interface:
  2. void add(Object item)

    //Adds item to the end of the Queue.
    boolean isEmpty()
    //Returns true if the Queue has no elements.
    Object peek()
    //Returns the top element without removing it.
    Object remove()
    //Returns and removes the first element.

  3. To declare a reference variable for a Queue, do the following:
  4. Queue <ClassName> myQ =
          new LinkedList <ClassName> ();

  5. This is an easy way to create a new Queue object without having to create a whole new class to implement the Queue interface. There are other ways to implement a Queue but this is the only way that AP requires.

  6. Here is a short example showing how to create, populate, and deconstruct a Queue.

    Queue <Integer> q = new LinkedList <Integer> ();

    for(int i = 1; i <= 5; 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, both loops print the exact same thing. This is because a Queue adds data to the end and takes data from the front, so it is going from the front to the end when removing data, just like the for each loop.

 

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