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?
When you initialize your array
there are
numRoutesslots all filled with their default value. For reference data types the default value isnull, so when you try to access theRouteobjects in your secondforloop they are allnull, you first need to initialize them somehow like this: