Java multiple keys direct to the same values

DsCpp :

Is there a way to points several keys to the same value?
i.e.

HashMap<String, Float> mymap = new HashMap<>();
mymap.put("hello",5f);
mymap.put("bye",5f);
~somehow point bye and hello to the same value~
mymap.put("bye", mymap.get("bye") +5f)

mymap.get("hello") == 10
Torben :

Java HashMap stores references to Objects. If you store same object with two different keys, the keys will point to the same value.

But that is not your problem. Your problem is that you are using Float values and Float is an immutable data type. You can not change it's value once it has been created. To achieve what you want to do you need to either create a mutable Float or store the float in a container and store that container in the map. One of the most simple containers would be a single element array (though I would only use it in an example code, never in a production code as it is error prone and it is "self undocumentable").

HashMap<String, Float[]> mymap = new HashMap<>();
Float[] val = new Float[] { 5f };
mymap.put("hello", val);
mymap.put("bye", val);
...
mymap.get("bye")[0] = mymap.get("bye")[0] + 5f;

mymap.get("hello")[0] == 10f

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115644&siteId=1