[英]Java Set<String> in a HashMap
I have this object: 我有这个对象:
Map<Long, Set<String>> resourcesByID = new HashMap<Long, Set<String>>();
and another: 另一个:
Set<String> resources;
When I want to put more Set into the HashMap it will override the elements of the Set, that I put into previously. 当我想将更多Set放入HashMap中时,它将覆盖我之前放入的Set的元素。 Why? 为什么? And how can I resolve this problem? 我该如何解决这个问题?
Assuming 假设
Long id = 1234L;
Set<String> resources = ...;
If you want to add another mapping from a Long
to a Set
then 如果要添加另一个从Long
到Set
映射,则
resourcesById.put(id, resources);
If you want to add String
s to an existing mapping 如果要将String
添加到现有映射
resourcesById.get(id).addAll(resources);
And to make life simpler if you're not doing initialization correctly... 如果您未正确进行初始化,则可以简化工作...
if (!resourcesById.containsKey(id)) {
resourcesById.put(id, new HashSet<String>());
}
resourcesById.get(id).addAll(resources);
If key
matches, it overrides the previous values, otherwise it won't override. 如果key
匹配,它将覆盖以前的值,否则将不覆盖。
(or) (要么)
As Thomas commented, if your set is mutate and you are updating the same set, yes, then it may override. 正如Thomas所言,如果您的集合是变异的,并且您要更新同一集合,是的,那么它可能会被覆盖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.