Note that there are some explanatory texts on larger screens.

plurals
  1. POUpdate HashMap values of type HashSet<Integer>
    primarykey
    data
    text
    <p>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:</p> <pre><code> public static void main(String[] args) { String[] mapKeys = new String[]{"hello", "world", "america"}; Map&lt;String, Set&lt;Integer&gt;&gt; hashMap1 = new HashMap&lt;String, Set&lt;Integer&gt;&gt;(); Set&lt;Integer&gt; values = new HashSet&lt;Integer&gt;(); for (int i = 0; i &lt; 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&lt;Integer&gt; 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()); } </code></pre> <p>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]</p> <p>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</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload