[英]2d Array of Object Arrays
我想制作一個二維數組,每個數組都充滿另一個對象。 到目前為止,我有:
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
這意味着數組為空。 關於如何解決它的任何想法?
這就是問題:
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字段,但這是另一回事。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.