Chr*_*ngj 0 java arrays generics
我正在创建一个由数组支持的泛型类型堆栈。当我尝试创建泛型类型数组时,Java 不允许我这样做。有人告诉我,我必须创建一个 Object 类型的数组并将其转换为泛型类型。我已将我的 Object 数组强制转换为 type ,但是如何处理 Java 不断给我的 Unchecked Type 错误?
public class AStack<T>{
// Create a stack with the default capacity 10. The stack expands
// its internal array when the number of elements pushed() into it
// would exceed the internal capacity.
Object arr[];
int top=-1;
public AStack(){
int defSize=10;
arr = (T[])new Object [defSize];
}
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止的地方。
更新:我正在创建一个 Object 数组,然后在方法结束时将返回类型转换为 T 类型。
最简单的方法是使用类型变量将对象数组转换为所需的类型。
public class AStack<T> {
T arr[];
int top=-1;
public AStack() {
int defSize=10;
arr = (T[]) new Object [defSize];
}
}
Run Code Online (Sandbox Code Playgroud)