Java stack


import java.util.Stack;
import java.util.Random;

public class TestStack {
	public static void main(String [] args){
		// create a new stack of strings
		Stack<String> stack = new Stack<String>();
		
		// push some strings onto the stack
		stack.push("apple");
		stack.push("banana");
		stack.push("kiwi");
		
		// Java allows you to print the entire stack
		System.out.println(stack);
		
		// pop the stack until it becomes empty
		while (!stack.empty()) {
			System.out.println(stack.pop());
		}
		
		// create a new stack of integers
		Stack<Integer> stackInt = new Stack<Integer>();
		stackInt.push(1);
		
		// peek at the top element, but keep it on the stack
		System.out.println(stackInt.peek());
		
		// the stack is not empty
		System.out.println(stackInt.empty());
		
		// empty the stack 
		stackInt.pop();
		
		// write a loop to store 100 random elements on the stack
		// the random elements are between 1 and 10 inclusive
		Random rand = new Random();
		
		for (int j = 0; j < 100; ++j) {
			stackInt.push(1 + rand.nextInt(10));
		}

		System.out.println(stackInt);
				
		// write a method to remove all elements from the stack that 
		// are > 5. Do not change the order of the remaining elements. 
		
		removeElements(stackInt);
		
		System.out.println(stackInt);
		
	}
	
	public static void removeElements(Stack<Integer> stack) {
		Stack<Integer> tempStack = new Stack<Integer>();
		
		while(!stack.empty()) {
			int item = stack.pop();
			if(item <= 5) {
				tempStack.push(item);
			}
		}
		
		while(!tempStack.empty()) {
			stack.push(tempStack.pop());
		}
	}
}

CSci 2101 course web site.