我已经用java泛型类型解决了我的鼻毛问题。我正在尝试创建一个我可以乱用的通用 2D 数组(这是 90% 的实验,10% 对类等有用)。我对我得到的错误有点困惑。我理解它对我大喊大叫的话,但我不明白它们或如何解决它。这是代码:
private T[][] grid;
private int size;
private int hw;
private int r_curr = 0;
private int c_curr = 0;
private Class<T> currclass;
@SuppressWarnings("unchecked")
public Array2D(Class<T> type, int r){
currclass = type;
hw = r;
size = r*r;
int count = 0;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
grid = (T[][]) Array.newInstance(type, r);
//TODO: This is the bit where I get the following error
//Exception in thread "main" java.lang.ClassCastException:
//[Ljava.lang.Boolean; cannot be cast to [[Ljava.lang.Object;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for(int i = 0; i < grid.length; i++){
grid[i] = (T[]) Array.newInstance(type, r);
for(int j = 0; j < grid.length; j++){
grid[i][j] = null;
count ++;
}
}
if(!(size == count)){
if(verbose){System.out.println("ALERT...Failed to successfully create array!");}
grid = (T[][]) Array.newInstance(type, r);
}
}
现在不要告诉我你在那里找到的其他损坏的东西(我确定它存在,哈哈),我还在写它,但泛型/铸造位让我难住了。
编辑:这是堆栈跟踪。这里真的没有太多。
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Boolean; cannot be cast to [[Ljava.lang.Object;
at mat.Array2D.<init>(Array2D.java:22)
at mat.BinMatrix.generateMatrix(BinMatrix.java:24)
at mat.BinMatrix.<init>(BinMatrix.java:9)
at mat.Test.main(Test.java:6)