Question 5
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
class ArrayStack<T> {
private T[] items = new T[10];
private int top;
void push(T x) { items[top++] = x; }
T pop() { return items[--top]; }
}
public class Main {
public static void main(String[] args) {
ArrayStack<String> s = new ArrayStack<>();
s.push("x");
System.out.println(s.pop());
}
}
- A top must be initialised to 0
- B Java cannot create an array of a type variable (type erasure); use an Object[] (casting on pop) or an ArrayList<T> Correct
- C Generic classes cannot have arrays
- D push must return T
Correct Answer: Option B
javac: "generic array creation". The usual workaround is Object[] items with @SuppressWarnings("unchecked") T pop() { return (T) items[--top]; }.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!