Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a Java Map <Integer, Double[]>, do I need to put the Double[] after getting and modifying?

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!

like image 470
obaqueiro Avatar asked Jul 27 '11 12:07

obaqueiro


People also ask

Can you put doubles in an int array?

You can have an array of Object s, in which case you can put Integer and Double objects in it.

How do I store duplicate keys on a Map?

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!

How do I change the value of a key in a HashMap in Java?

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.


1 Answers

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...

like image 139
Jon Skeet Avatar answered Sep 28 '22 07:09

Jon Skeet