user1732178
user1732178

Reputation: 23

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. Why? And how can I resolve this problem?

Upvotes: 2

Views: 2396

Answers (3)

ptomli
ptomli

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 Strings 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

zaffargachal
zaffargachal

Reputation: 810

  • 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.

Upvotes: 2

kosa
kosa

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

Related Questions