A quick question which maybe is lame.
In the following code:
Map<Integer, Double[]> dataMap = new Map<Integer, Double[]>();
dataMap.put(1, new Double[]{100,100});
Double[] dob = dataMap.get(1);
dob[0] = 100;
dob[1] = 200;
dataMap.put(1, dob);
Is the last "dataMap.put" instruction necessary? or will the dataMap.get(1) yield a reference to the array which will then be modified directly in the later statements.
I know that, in the case of mutable objects (e.g. Map), Map.get() will give me the reference to the desired object, however with an array of Doubles (whose element type e.g. Double
are immutable) I am not sure if I get a reference to the array in the Map.
Thanks!
You can have an array of Object s, in which case you can put Integer and Double objects in it.
You can use a TreeMap with a custom Comparator in order to treat each key as unequal to the others. It would also preserve the insertion order in your map, just like a LinkedHashMap. So, the net result would be like a LinkedHashMap which allows duplicate keys!
hashmap. put(key, hashmap. get(key) + 1); The method put will replace the value of an existing key and will create it if doesn't exist.
No, the final statement isn't necessary - because the map only contains references to arrays, as you've mentioned. An array is a mutable object, even though Double
isn't - it's like having an object with a setName(String)
method - just because String
is immutable, the container type isn't.
Note that if you do this, another thread1 may see half the change (i.e. the setting of the first element to 100) without seeing the second element set to 200. Is that okay? If not, you could think about creating a new array instead:
Map<Integer, Double[]> dataMap = new HashMap<Integer, Double[]>();
dataMap.put(1, new Double[]{100,100});
// Other stuff...
// Replace value in map with a reference to a different array.
Double[] dob = new Double[] { 100, 200 };
dataMap.put(1, dob);
1 This is assuming you're using a thread-safe map to start with, of course...
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