Faux Pas
Faux Pas

Reputation: 536

Changing a particular value of an array, in Java, when it is a value of a HashMap

I have a HashMap where the Key is an integer and the value is an array of double i.e.,

HashMap<Integer, double[]> map = new HashMap<>();

How do I change the value of a particular index in the double array?

One way of doing it is to get the double array for the required key, copy it to a temp array, modify the required index in the temp array and then, put the array into the map, for the same key i.e.,

double temp[] = map.get(i);

temp[10] = 3.142;

map.put(i,temp);

But, there must be a better implementation, right?

Upvotes: 2

Views: 994

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198143

There's a misconception here. Your answer is already nearly the correct one, but it's better than you think it is. double[] temp = map.get(i) does not make a copy: it returns a reference to the same array. So

double[] temp = map.get(i);
temp[j] = 42.0;

does what you want it to do already.

Upvotes: 2

Stephen C
Stephen C

Reputation: 718946

This should do the trick ... unless there is something about your problem description that I've misunderstood:

HashMap map = new HashMap<Integer, double[]>();
...
doubles = map.get(i);
doubles[j] = 42.0;

Upvotes: 1

Related Questions