Reputation: 23
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. Why? And how can I resolve this problem?
Upvotes: 2
Views: 2396
Reputation: 11818
Assuming
Long id = 1234L;
Set<String> resources = ...;
If you want to add another mapping from a Long
to a Set
then
resourcesById.put(id, resources);
If you want to add String
s to an existing mapping
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);
Upvotes: 2
Reputation: 810
Upvotes: 2
Reputation: 66637
If key
matches, it overrides the previous values, otherwise it won't override.
(or)
As Thomas commented, if your set is mutate and you are updating the same set, yes, then it may override.
Upvotes: 0