0

When I run the following code:

class MyStack<T>
{
    private T[] stack;
    ... private T top;
    private static final int size=50;

    public MyStack()
    {
      stack = new int[size];
      top = 0;
    } 
}

I get this error

MyStack.java:18: generic array creation

stack = new T[size];
...
1 error

What should the proper code be, so I dont get this error

0

1 Answer 1

6

You cannot instantiate a parameterized type in Java. and thus also not create arrays of it. Replace T[] by Object[] and create it as new Object[] and use casts against T in the methods whenever necessary.

Only if Java had Reified generics, it would be possible.

Sign up to request clarification or add additional context in comments.

3 Comments

I'd start to take a look in source code of java.util.Stack.
Nah, better look at ArrayList. The Stack class is only a subclass of Vector, so we don't even see the array there.
@Paulo: ArrayList isn't a stack. An ArrayDeque would be better, but that's pretty complicated for a student. Also if OP knows basic Java, he should understand what class Stack extends Vector means and in any IDE you should be able to (Ctrl)click just Vector to see its source code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.