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