I have a curious situation - there is a HashMap, that is initialized as follows:
HashMap<String, HashSet<String>> downloadMap = new HashMap<String, HashSet<String>>();
and then I have the following things, that will be executed indefinitely via a quartz scheduler:
myHashSet = retrieve(animal);
downloadMap.put(myKey, myHashSet);
// do stuff
downloadMap.get(myKey).clear();
What happens after, is that one value gets associated with the different keys. So, for instance, I will have things like:
Kitens [cute kitten, sad kitten]
Puppies [cute kitten, sad kitten]
Which never should happen.
Particularly, after I retrieve the HashSet of the kittens:
myHashSet = retrieve(animal);
myHashSet = [cute kitten, sad kitten] downloadMap = Kittens [], Puppies[]
then put() is executed and I get:
downloadMap = Kitens [cute kitten, sad kitten], Puppies [cute kitten, sad kitten]
Does anyone knows why this is the case?
Thank you in advance!
Looks like you use the same HashSet<String> reference in all your values of the HashMap<String, HashSet<String>>. Knowing this, the problem is how you insert the HashSet<String>s in your HashMap. Note that you must use a new HashSet<String> reference for every key-value pair.
Update your question accordingly to receive a more specific answer.
Not directly associated to the real problem, it is better to program oriented to interfaces instead of direct class implementations. With this, I mean that you should declare the downloadMap variable as
Map<String, Set<String>> downloadMap = new HashMap<String, Set<String>>();
Similar for the Sets that will be put in this map.
More info:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With