0

I have a section of code like this:

    Map<Integer, Map<Integer, Integer>> hashMap = new HashMap<>();
    for (int[] time : times) {
        if (!hashMap.containsKey(time[0])) {
            hashMap.put(time[0], new HashMap<Integer, Integer>());
        }
        hashMap.get(time[0]).put(time[1], time[2]);
    }

Inside this code, time is an array with 3 elements (e.g [0, 1, 2]), and times is made up of such array. I first stored elements like this but when I access the map later, it throws a NullPointerException. Does it mean that the map actually stores nothing?

xunmiw
  • 7
  • 2

1 Answers1

0

Your code looks correct. After you run it, if time[] is { 0, 1, 2 }, I would expect

System.out.println(hashMap.get(0).get(1))

would output "2".

Check your code for accessing the map.

Note that if you try with a different top-level key, e.g.

int x = hashMap.get(3).get(4);

you would get a NullPointerException , since hashMap.get(3) returns null

Andrew McGuinness
  • 2,092
  • 13
  • 18