在Java中的类实例中初始化变量数组

时间:2012-12-21 06:39:26

标签: java nullpointerexception

我来自C背景,并且遇到了Java问题。目前,我需要初始化对象数组中的变量数组。

我在C中知道它类似于malloc-ing int数组中的structs数组,类似于:{/ p>

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。我做错了什么,有更好的方法吗?

3 个答案:

答案 0 :(得分:4)

初始化数组时

Route[] route = new Route[numRoutes];

numRoutes个插槽全部填充了默认值。对于参考数据类型,默认值为null,因此当您尝试访问第二个Route循环中的for个对象时,它们都是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];

答案 1 :(得分:1)

Route[] route = new Route[numRoutes];

在创建对象数组的java中,所有插槽都使用默认值声明,如下所示     Objects = null 原语     int = 0     boolean = false

这些numRoutes槽都填充了它们的默认值,即null。当您尝试访问循环中的Route对象时,数组引用指向null,您首先需要以某种方式初始化它们:

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

答案 2 :(得分:0)

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