当前位置: 动力学知识库 > 问答 > 编程问答 >

java - What is wrong with my code?

问题描述:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: