我正在创建一个由数组支持的泛型类型堆栈。当我尝试创建泛型类型数组时,Java 不允许我这样做。有人告诉我必须创建一个对象类型的数组并将其转换为泛型类型。我已将 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];
}
这就是我目前所处的位置。
更新: 我正在创建一个对象数组,然后在方法末尾将返回类型转换为 T 类型。
最佳答案
最简单的方法是使用类型变量将对象数组转换为所需的类型。
public class AStack<T> {
T arr[];
int top=-1;
public AStack() {
int defSize=10;
arr = (T[]) new Object [defSize];
}
}
关于java - 将对象数组转换为泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36968462/