这是我的地图
HashMap<String, Set<String>> hmap = new HashMap<>();
我想从Set
中检索Map
并为其添加元素。
Set<String> val = hmap.get(key);
val.add(newElement); //NPE
hmap.put(key, val);
但我在NullPointerException
行
val.add
这可能是微不足道的,但我没有看到它..
我错过了什么?
答案 0 :(得分:1)
请尝试以下选项:
HashMap<String, Set<String>> hmap = new HashMap<>();
Set<String> val = hmap.get(key);
if (val == null) {
val = new HashSet<>();
val.add(newElement);
hmap.put(key, val);
}
else {
val.add(newElement);
}
答案 1 :(得分:1)
如果您正在编写修改给定键的地图条目的代码,最好首先检查该特定键是否存在值。
示例:
if (hmap.contains(key) == false)
{
// This will prevent the null reference issue
hmap.put(key, new HashSet<String>());
}
Set<String> val = hmap.get(key);
val.add(newElement);
另外,作为旁注:
hmap.put(key, val);
不需要那条线。 “val”是对地图中现有集合的引用。修改它将修改映射到key的值,因此您不需要调用put。它已经存在并且已经更新。
答案 2 :(得分:1)
如果地图中没有该键,您可以使用Map.computeIfAbsent()
添加值。
请注意,该方法返回与指定键关联的当前(现有或已计算)值。因此,您可以使用返回的对象在Set对象中添加String对象:
String key = "a key";
Set<String> val = hmap.computeIfAbsent(key, k-> new HashSet<>()); // create the hashset and associate it to the key if key not present
val.add("a value");
答案 3 :(得分:0)
这就是实际发生的事情
Map<String, Set<String>> map = new HashMap<String, Set<String>>();
map.put("1_a", new HashSet<String>());
Set<String> set1 = map.get("1_a");
set1.add("a");
System.out.println(set1);
Set<String> set2 = map.get("1_b"); // Not present
set2.add("a"); // NPE - set2 will be null.
您可以添加@Stephano提到的支票,它总是很方便。
答案 4 :(得分:0)
为了简短起见,你也可以这样做:
HashMap<String, Set<String>> hmap = new HashMap<>();
String key = "key";
String newElement = "ele";
if (!hmap.containsKey(key)) {
hmap.put(key, new HashSet<>());
}
hmap.get(key).add(newElement);