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 >  
 

B. The Java Stack Class page 4 of 10

  1. The AP subset requires students to know the following methods of the java.util.Stack:
  2. boolean empty()
    //Returns true if the Stack has no elements.
    Object peek()
    //Returns the top element without removing it.
    Object pop()
    //Returns and removes the top element.
    Object push(Object item)
    //Adds item to the top of the Stack.

  3. To declare a reference variable for a Stack, do the following.
  4. Stack <ClassName> myStack =
          new Stack <ClassName> ();

  5. Here is a short example showing how to create, populate, and deconstruct a Stack:

    Stack <Integer> s = new Stack <Integer> ();

    for(int i = 1; i <= 5; i++){
        s.push(i);
    }

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

    while(!s.empty()){
        System.out.println(s.pop());
    }

    Output:

    1
    2
    3
    4
    5
    5
    4
    3
    2
    1

    Notice that the output first prints up to five and then comes back down again. The for each loop is only treating the Stack like a List, so it is not popping any of the data off the Stack. Therefore, during the while loop, the Stack is not empty and can still be used. Also, the for each loop will start at the beginning of the List and go to the end. Because Stacks deal with all the data transactions at the top (end) of the Stack, the for each will go in the opposite order that the pop method will.

 

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