LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java – Find the Error · Question 5

Error: new T[10] in a generic stack Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links