我正在创建一个由数组支持的泛型堆栈。当我尝试创建泛型类型数组时,Java不允许我这样做。有人告诉我必须创建一个Object类型的数组,并将其转换为泛型类型。我已经将对象数组强制转换为type,但是如何处理Java不断给我的未检查的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。
发布于 2016-05-01 23:50:09
最简单的方法是使用type变量将对象数组转换为所需的类型。
public class AStack<T> {
T arr[];
int top=-1;
public AStack() {
int defSize=10;
arr = (T[]) new Object [defSize];
}
}发布于 2016-05-01 23:47:50
您可以使用扩展到所有其他要泛型的类的接口或类,然后使用该接口或类作为数组的类型,现在可以将特定类型插入到数组中。
GenericType[] array = { new specificType1(), new specificType2(), new specificType3() }https://stackoverflow.com/questions/36968462
复制相似问题