简体   繁体   中英

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:

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM