我想制作一个数组的二维数组,每个数组都填充另一个对象。到目前为止我所拥有的是:
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
我一直在接受
java.lang.ArrayIndexOutOfBoundsException: 0
这意味着数组为空。知道怎么解决它?
答案 0 :(得分:5)
这是问题所在:
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];
}
}
(我还建议更改为更有意义的名称,并使用私有的最终字段,但这是另一回事。)