1

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

csgillespie
  • 54,386
  • 13
  • 138
  • 175
Dave
  • 11
  • 1
  • 1
    possible duplicate of [Error: Generic Array Creation](http://stackoverflow.com/questions/3865946/error-generic-array-creation) – Michelle Tilley Apr 03 '11 at 00:51

1 Answers1

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.

Community
  • 1
  • 1
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
  • 1
    I'd start to take a look in source code of `java.util.Stack`. – BalusC Apr 03 '11 at 00:55
  • Nah, better look at ArrayList. The Stack class is only a subclass of Vector, so we don't even see the array there. – Paŭlo Ebermann Apr 03 '11 at 01:51
  • @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. – BalusC Apr 03 '11 at 02:58