3

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

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

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. 我做错了什么,有没有更好的方法来做到这一点?

4

3 回答 3

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];
于 2012-12-21T06:43:35.617 回答
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];
  }
于 2012-12-21T06:52:48.457 回答
0
for (int i = 0; i < numRoutes; i++) {
  route[i] = new Route();
  route[i].departureTimes = new int[count];
于 2012-12-21T06:46:37.717 回答