我不确定为什么我会收到错误/警告"必需:T[] 找到:对象[]"和" T 扩展在类堆栈中声明的对象"


**//generic class** 
public class Stack <T> {
*instance variables below*
private int top=1;

private T[] stackArray;

private int stackSize;
*constructor*
public Stack(int size){


**this is where im getting the warning "[unchecked] unchecked cast"**
this.stackArray = (T[] )new Object[size];


*stack pointer and the stack size*
top=-1;
this.stackSize=size;

}

不能创建T[]的泛型数组。

例如,将T[]设置为Object[]

public class Stack <T> {
*instance variables below*
private int top=1;

private Object[] stackArray;

private int stackSize;
*constructor*
public Stack(int size){

this.stackArray = new Object[size];


*stack pointer and the stack size*
top=-1;
this.stackSize=size;

}

您需要在get操作上执行(T)stackArray[i],但要了解更多细节,请查看java.lang.ArrayList的实现。

否则你可能需要一个"sample"在构造函数中构造一个T[]数组,然后构造一个该类型的new:

public Stack(T[] array, int size){

this.stackArray = (T[]) Array.newInstance(array.getClass().getComponentType(), size);


*stack pointer and the stack size*
top=-1;
this.stackSize=size;

}

或者您可以使用生成器方法:

public Stack(IntFunction<T[]> generator, int size){

this.stackArray = generator.apply(size);


*stack pointer and the stack size*
top=-1;
this.stackSize=size;

}

可以这样调用:

Stack<String> stack = new Stack<>(String[]::new,10);

这是有效的,因为你可以把数组构造函数看作一个以int作为参数并返回数组T[] (public static <T> T[] arrayConstructor(int size){...})的方法

额外提示:你可以用这个方法缓存任何构造函数,只要你有一个与构造函数匹配的函数接口:

@FunctionalInterface
public interface Constructor {
Foo ctor(Bar b, int i, String s);
}
class Foo {
public Foo(Bar b, int i, String s) {...}
}
Constructor ctor = Foo::new; // <- constructor of Foo that can be passed as a variable.

最新更新