Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap put method clarification

Tags:

java

hashmap

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!

like image 978
user2187935 Avatar asked Feb 12 '26 01:02

user2187935


1 Answers

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:

  • What does it mean to "program to an interface"?
like image 184
Luiggi Mendoza Avatar answered Feb 14 '26 14:02

Luiggi Mendoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!