2012-12-21 39 views
3

我來自C背景,並且正在運行Java中的問題。目前,我需要在一個對象數組中初始化一個變量數組。在Java中的類實例中初始化一個變量數組

我知道在C中,它是類似於malloc-ingstructs一個陣列內等的int數組:

typedef struct { 
    char name; 
    int* times; 
} Route_t 

int main() { 
    Route_t *route = malloc(sizeof(Route_t) * 10); 
    for (int i = 0; i < 10; i++) { 
    route[i].times = malloc(sizeof(int) * number_of_times); 
    } 
... 

到目前爲止,在Java中我有

public class scheduleGenerator { 

class Route { 
     char routeName; 
    int[] departureTimes; 
} 

    public static void main(String[] args) throws IOException { 
     /* code to find number of route = numRoutes goes here */ 
     Route[] route = new Route[numRoutes]; 

     /* code to find number of times = count goes here */ 
     for (int i = 0; i < numRoutes; i++) { 
     route[i].departureTimes = new int[count]; 
... 

但它吐出一個NullPointerException。我做錯了什麼,有沒有更好的方法來做到這一點?

+0

你需要的路線[I]路線之前=新幹線()[我] .departureTimes = new int [count]; – aviad

+0

[李爾在這裏](http://www.tutorialspoint.com/java/java_arrays.htm) –

+0

爲什麼不使用構造函數,如果你只需要初始化它 –

回答

4

當你初始化數組

Route[] route = new Route[numRoutes]; 

numRoutes插槽都充滿了他們的默認值。對於引用數據類型的默認值是null,所以當你試圖訪問你的第二個for環路Route對象,他們都null,你首先需要以某種方式初始化它們是這樣的:

public static void main(String[] args) throws IOException { 
     /* code to find number of route = numRoutes goes here */ 
     Route[] route = new Route[numRoutes]; 

     // Initialization: 
     for (int i = 0; i < numRoutes; i++) { 
      route[i] = new Route(); 
     } 

     /* code to find number of times = count goes here */ 
     for (int i = 0; i < numRoutes; i++) { 
     // without previous initialization, route[i] is null here 
     route[i].departureTimes = new int[count]; 
+0

+1我會結合這兩個循環。 –

+2

是的,我也會在_real_代碼中。把它放在這裏強調,在使用它們之前初始化數組中的對象是很重要的。 – jlordo

0
for (int i = 0; i < numRoutes; i++) { 
    route[i] = new Route(); 
    route[i].departureTimes = new int[count]; 
1
Route[] route = new Route[numRoutes]; 

在java中在創建對象的陣列,所有時隙被聲明用有默認值如下 對象= NULL 原語 INT = 0 布爾=假

這些numRoutes插槽全部用它們的缺省值填充,即空。當您嘗試訪問路徑在循環數組引用指向空對象,你首先需要以某種方式初始化它們是這樣的:

// Initialization: 
    for (int i = 0; i < numRoutes; i++) { 
     route[i] = new Route(); 
     route[i].departureTimes = new int[count]; 
    }