Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an array of variables within a class instance in Java

I'm coming from a C background, and am running into a problem in Java. Currently, I need to initialize an array of variables within an array of objects.

I know in C it would be similar to malloc-ing an array of int within an array of structs like:

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);
  }
...

So far, in Java I have

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];
...

But its spitting out a NullPointerException. What am I doing wrong, and is there a better way to do this?

like image 485
PhaZePhyR Avatar asked Jul 21 '26 18:07

PhaZePhyR


2 Answers

When you initialize your array

Route[] route = new Route[numRoutes];

there are numRoutes slots all filled with their default value. For reference data types the default value is null, so when you try to access the Route objects in your second for loop they are all null, you first need to initialize them somehow like this:

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];
like image 174
jlordo Avatar answered Jul 24 '26 08:07

jlordo


Route[] route = new Route[numRoutes];

In java when you create an array of Objects, all the slots are declared with there default values as below Objects = null primitives int = 0 boolean = false

these numRoutes slots all filled with their default value i.e. null. When you try to access the Route objects in your loop the array reference is pointing to null, you first need to initialize them somehow like this:

  // Initialization:
  for (int i = 0; i < numRoutes; i++) {
       route[i] = new Route();
       route[i].departureTimes = new int[count];
  }
like image 35
pratikch Avatar answered Jul 24 '26 07:07

pratikch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!