2

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?

3
  • 3
    Can you give an example in which case this happens? How do you put the Sets into the HashMap? Commented Oct 9, 2012 at 15:18
  • You should post the code where you are using resourcesById. It is likely you are just putting a new Set into the HashMap. What you should do is check if the HashMap contains the Long you are about to use to insert. If it does, you must get the Set from the map and add all elements from the insertion Set into it. If it does not, just insert your insertion set. Commented Oct 9, 2012 at 15:19
  • 2
    It is likely you're not creating a new Set for each new key, and instead you are constantly pushing new elements into the same resources object then putting multiple references to said resources object for various keys into the hashmap. Commented Oct 9, 2012 at 15:20

3 Answers 3

2
  • 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.
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

0

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.

3 Comments

Or worse, if you mutate the already inserted set from outside.
@user1732178: Keys are different, but you are updating same Set?
This was my problem: when i put the different elements into the HashMap, i use the same Set reference so it change all Sets in the HashMap. But now it works. Thanks a lot. That mutate comment helped ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.