问题描述:

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

网友答案:

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.

相关阅读:
Top