2012-12-21 41 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]; 
    }