-1

我想制作一个二维数组,每个数组都填充了另一个对象。到目前为止,我所拥有的是:

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

这意味着数组是空的。知道如何解决吗?

4

1 回答 1

5

这就是问题:

class Setup {
    int wpb;
    CustomCache[] wpbArray = new CustomCache[wpb];
    public Setup(int a){
        wpb = a;
    }
}

这一行:

CustomCache[] wpbArray = new CustomCache[wpb];

在构造函数的主体之前运行- whilewpb仍然是 0。你想要:

class Setup {
    int wpb;
    CustomCache[] wpbArray;

    public Setup(int a) {
        wpb = a;
        wpbArray = new CustomCache[wpb];
    }
}

(我还建议更改为更有意义的名称,并使用私有 final 字段,但这是另一回事。)

于 2013-05-01T19:23:27.307 回答