- The AP subset requires students to know the following methods of the
java.util.Stack
:
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.
- To declare a reference variable for a Stack, do the following.
Stack <ClassName> myStack =
new Stack <ClassName> ();
- 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.