如何将值存储在嵌套的地图中?

huangapple 未分类评论43阅读模式
英文:

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&lt;Integer, Map&lt;Integer, Integer&gt;&gt; hashMap = new HashMap&lt;&gt;();
    for (int[] time : times) {
        if (!hashMap.containsKey(time[0])) {
            hashMap.put(time[0], new HashMap&lt;Integer, Integer&gt;());
        }
        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

huangapple
  • 本文由 发表于 2020年7月24日 18:07:27
  • 转载请务必保留本文链接:https://java.coder-hub.com/63071432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定