I have trouble updating the HashMap values of Set type. After initializing the HashMap with key-values pair, I want to insert a new value to the the existing value Set, and the new value is to be incremented for each insert. My code is following:
public static void main(String[] args)
{
String[] mapKeys = new String[]{"hello", "world", "america"};
Map<String, Set<Integer>> hashMap1 = new HashMap<String, Set<Integer>>();
Set<Integer> values = new HashSet<Integer>();
for (int i = 0; i < 10; i++) // initialize the values to a set of integers[1 through 9]
{
values.add(i);
}
for (String key : mapKeys)
{
hashMap1.put(key, values);
}
StdOut.println("hashMap1 is: " + hashMap1.toString());
int newValues = 100; // insert this newValues (incremented at each insert) to each value
Set<Integer> valuesCopy;
for (String key : mapKeys)
{
if (hashMap1.containsKey(key))
{
valuesCopy = hashMap1.get(key); // first, copy out the existing values
valuesCopy.add(newValues++); // insert the newValues to the value Set
hashMap1.remove(key);// remove the existing entries
hashMap1.put(key, valuesCopy); // insert the key-value pairs
}
}
StdOut.println("the updated hashMap1 is: " + hashMap1.toString());
}
When executing the code, each HashMap key is associated with the same set of Integers: [102, 0, 1, 2, 100, 3, 101, 4, 5, 6, 7, 8, 9], however, what I really want is insert only one number to each set, this is what I want: [0, 1, 2, 100, 3, 4, 5, 6, 7, 8, 9]
I need help understanding this: why all the new inserted values are the same? how to make it work as I wish? thanks for help