簡體   English   中英

在Java中的類實例中初始化變量數組

[英]Initializing an array of variables within a class instance in Java

我來自C背景,並且遇到了Java問題。 目前,我需要初始化對象數組中的變量數組。

我在C中知道它類似於在structs數組中malloc-ing 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 我做錯了什么,是否有更好的方法來做到這一點?

初始化陣列時

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];
Route[] route = new Route[numRoutes];

在java中創建一個Objects數組時,所有的槽都是用默認值聲明的,如下所示Objects = null primitives 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];
  }
for (int i = 0; i < numRoutes; i++) {
  route[i] = new Route();
  route[i].departureTimes = new int[count];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM