英文:
How to store value in a map inside map?
问题
我有一个类似这样的代码段:
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]);
}
在这段代码中,time
是一个包含3个元素的数组(例如 [0, 1, 2]),而 times
由这样的数组组成。起初我是这样存储元素的,但当我稍后访问该映射时,它会抛出一个 NullPointerException
。这是否意味着该映射实际上未存储任何内容?
英文:
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?
答案1
得分: 0
你的代码看起来是正确的。在你运行它之后,如果 time[]
是 { 0, 1, 2 }
,我期望以下代码:
System.out.println(hashMap.get(0).get(1))
会输出 "2"。
检查你的代码以访问这个映射。
请注意,如果你尝试使用不同的顶层键,例如:
int x = hashMap.get(3).get(4);
你会得到一个空指针异常,因为 hashMap.get(3)
会返回 null。
英文:
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
专注分享java语言的经验与见解,让所有开发者获益!
评论