2013-05-01 105 views
-1

我想製作一個數組的二維數組,每個數組都填充另一個對象。我至今是:2d對象數組陣列

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 

這意味着數組爲空。任何想法如何解決它?

回答

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]; 
    } 
} 

(我也建議改爲更有意義的n但是這是另一回事。)

+0

你真了不起... – Failsafe 2013-05-01 19:24:46

+0

從來沒有把你的答案標記爲正確的答案。對於那個很抱歉。 – Failsafe 2014-08-01 12:12:15