简体   繁体   English

Java集 <String> 在HashMap中

[英]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 如果要添加另一个从LongSet映射,则

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);
  • First reason you may be using same key for each set. 第一个原因是您可能对每个集合使用相同的密钥。
  • Second reason if key is different than for each key (long) you might be using same Set using resources reference, you have to create the separate instance of Set for each key. 第二个原因是,如果密钥与每个密钥(长整数)不同(您可能使用资源引用使用同一Set),则必须为每个密钥创建Set的单独实例。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM