Write a generic class GenericStack<E> backed by a private ArrayList<E>, with:
void push(E item)E pop()andE peek()— both throwIllegalStateExceptionwhen the stack is emptyboolean isEmpty()andint size()String toString()— the elements from top to bottom separated by single spaces, oremptywhen 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