Write a reusable generic data structure and use it for two kinds of data at once.
What to build
A generic stack used for numbers and for words.
Requirements
- Write
class Stack<T>withpush,pop,peek,sizeandisEmpty;popandpeekthrowIllegalStateException("empty")when there is nothing. - Keep a
Stack<Integer>and aStack<String>. Commands:num Nandword Wpush;popnumandpopwordpop and print the value;sizeprintsnumbers: A, words: B. A pop on an empty stack printsempty.
Input
Line 1: q. Then q commands.
Output
One line per pop and size command.
Constraints
1 ≤ q ≤ 100.
Example
Input:
6
num 3
num 4
word hi
popnum
size
popword
Output:
4
numbers: 1, words: 1
hi
Why it works
The class is written once for any T, so the two stacks share the code but keep their types: popnum gives an Integer and popword a String.
Examples
Example 1 · Input
6 num 3 num 4 word hi popnum size popword
Expected output
4 numbers: 1, words: 1 hi
Example 2 · Input
2 popword size
Expected output
empty numbers: 0, words: 0
Hints
Hint 1
class Stack<T> backed by an ArrayList<T>; pop removes the last item.
Hint 2
Make pop and peek throw an IllegalStateException on an empty stack, and catch it in main.
Solution
Show one correct solution (try it yourself first)
import java.util.*;
public class Main {
static class Stack<T> {
private final List<T> items = new ArrayList<>();
void push(T item) { items.add(item); }
T pop() {
if (items.isEmpty()) throw new IllegalStateException("empty");
return items.remove(items.size() - 1);
}
T peek() {
if (items.isEmpty()) throw new IllegalStateException("empty");
return items.get(items.size() - 1);
}
int size() { return items.size(); }
boolean isEmpty() { return items.isEmpty(); }
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = Integer.parseInt(in.nextLine().trim());
Stack<Integer> numbers = new Stack<>();
Stack<String> words = new Stack<>();
for (int i = 0; i < q; i++) {
String[] p = in.nextLine().split(" ");
try {
switch (p[0]) {
case "num" -> numbers.push(Integer.parseInt(p[1]));
case "word" -> words.push(p[1]);
case "popnum" -> System.out.println(numbers.pop());
case "popword" -> System.out.println(words.pop());
default -> System.out.println("numbers: " + numbers.size() + ", words: " + words.size());
}
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
}
}