Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Best way to update HashMap value - Pass by value/reference related

I have a HashMap with some data. Looking at the following code...

HashMap<String, Double[]> map; //Already populated with data

Double[] results = map.get(key);
updateArray(results); //This function makes changes to the results array.
map.put(key, results);

...my question is whether or not the map.put(key, results) is even necessary?

I am still a little confused about the pass-by-value and pass-by-reference nature of Java. To be clear, in the first line of code, we are getting a reference to the Double array, correct? As such, the function on the second line should properly update the Double array in the HashMap... which would then seemingly make the map.put() on the third line redundant.

Looking at other people's HashMap related code, they always seem to be using the put() method. I just wanted to make sure that there aren't any unforeseen consequences of doing it without the put() method.

Thanks for any input!

like image 425
Fitzy123 Avatar asked Aug 20 '14 15:08

Fitzy123


2 Answers

Map.get(Object) simply returns a reference to said array, it does not copy the array's contents to a new array. Therefore any changes you make to the array returned by Map.get(Object) will be reflected in the one stored in the Map because they are the same array. This therefore makes calling Map.put(Object,Object) in this situation completely redundant.

like image 142
DeathByTensors Avatar answered Oct 12 '22 12:10

DeathByTensors


If you're modifying the object referenced by the reference value that you retrieved from the HashMap, there is no point replacing its entry in that same HashMap.

If you're modifying the reference, then you do need to replace it.

like image 42
Sotirios Delimanolis Avatar answered Oct 12 '22 12:10

Sotirios Delimanolis