I have a hashmap which has a hashset of strings as values. I worked out a test code - shown below :
public static void main(String args[]) {
HashMap<String, HashSet<String>> hmap = new HashMap<String, HashSet<String>>();
HashSet<String> set = new HashSet<String>();
set.add("a");
set.add("b");
set.add("c");
set.add("d");
hmap.put("a", set);
set.clear();// = new HashSet<String>();
set.add("a");
set.add("b");
hmap.put("c", set);
set.clear();// = new HashSet<String>();
set.add("a");
set.add("b");
set.add("c");
hmap.put("b", set);
for (Entry<String, HashSet<String>> entry : hmap.entrySet())
{
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
I am reusing the same hashset to populate the values in the hashmap. But I see that hashset.clear() is not clearing the values as expected.
The code I get for the above code is -
b - [b, c, a]
c - [b, c, a]
a - [b, c, a]
So, the all the values are overwritten by the last HashSet. I read javadoc for clear() and the expected behavior is that the elements of the hashset are removed on calling clear.
Output when I use new HashSet instead of hashset.clear()
b - [b, c, a]
c - [b, a]
a - [d, b, c, a]
This is the output I am expecting.
The reason I do not want to use set = new HashSet<String>
each time is because I do not want create too many hashsets ( the size of hashmap is expected to be large). Am I missing something?
Thanks for your help.