THINK FIRST·CODE LATER

← All labs

A Generic Stack Driven by Commands

Problem

Write a generic class GenericStack<E> backed by a private ArrayList<E>, with:

  • void push(E item)
  • E pop() and E peek() — both throw IllegalStateException when the stack is empty
  • boolean isEmpty() and int size()
  • String toString() — the elements from top to bottom separated by single spaces, or empty when there are none

Then write a program that creates a GenericStack<String>, reads a number q and then q commands, one per line:

Command Output
push X nothing (X is a single word)
pop Popped: X, or Error: empty stack
peek Top: X, or Error: empty stack
size Size: n

The program must catch the IllegalStateException to print the error message. After the last command, print Final (top first): followed by the stack's toString().

Input:

6
push red
push green
peek
pop
push blue
size

Output:

Top: green
Popped: green
Size: 2
Final (top first): blue red

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.