我想创建一个2D数组,每个数组都填充了另一个对象。目前我得到的是:
class CustomCache{
boolean dirty = false;
int age = 0;
String addr;
public CustomCache(boolean a, String b, int c){
dirty = a;
addr = b;
age = c;
}
}
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
Setup[][] array = new Setup[numSets][numBlocks];
for(int i=0; i<numSets; i++){
for(int j=0; j<numBlocks; j++){
array[i][j] = new Setup(wpb);
for(int k=0; k<wpb; k++){
array[i][j].wpbArray[k] = new CustomCache(false, "", 0);
}
}//end inner for
}//end outer loop
我一直得到a
java.lang.ArrayIndexOutOfBoundsException: 0
表示数组为空。知道怎么修吗?
这就是问题所在:
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
这条线:
CustomCache[] wpbArray = new CustomCache[wpb];
在构造函数体之前运行—当wpb
仍然为0时。你想要的:
class Setup {
int wpb;
CustomCache[] wpbArray;
public Setup(int a) {
wpb = a;
wpbArray = new CustomCache[wpb];
}
}
(我也建议更改为更有意义的名称,并使用私有final字段,但这是另一回事。)