[英]2d Array of Object Arrays
I want to make a 2D array of Arrays, each filled with another object. 我想制作一个二维数组,每个数组都充满另一个对象。 What I have so far is: 到目前为止,我有:
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
I keep getting a 我不断得到
java.lang.ArrayIndexOutOfBoundsException: 0
Which means the array is empty. 这意味着数组为空。 Any idea of how to fix it? 关于如何解决它的任何想法?
This is the problem: 这就是问题:
class Setup {
int wpb;
CustomCache[] wpbArray = new CustomCache[wpb];
public Setup(int a){
wpb = a;
}
}
This line: 这行:
CustomCache[] wpbArray = new CustomCache[wpb];
runs before the body of the constructor - while wpb
is still 0. You want: 在wpb
仍为0时在构造函数的主体之前运行。您需要:
class Setup {
int wpb;
CustomCache[] wpbArray;
public Setup(int a) {
wpb = a;
wpbArray = new CustomCache[wpb];
}
}
(I also suggest changing to more meaningful names, and using private final fields, but that's a different matter.) (我还建议更改为更有意义的名称,并使用私有的final字段,但这是另一回事。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.