Skip to content
Advertisement

How link multiple keys to the same value in the HashMap

I am trying to link the value of a key to another key’s value but cannot seem to get it working.

For example, if I’m creating a HashMap and adding a key-value pair ("x", 0) to it. I then want to be able to add other keys mapped to the same value as the first one.

So if I have ("x", map.get("y")) and ("y", 0) I want to be able somehow to link it. So that if I now update a value for "y" key like that ("y", 10), then I expect that map.get("x") should also return 10.

JavaScript

I can’t figure out how to get this working as x always gets the value of what y is now, and not what y is at the time of printing the value.

Advertisement

Answer

If you want to associate a group of keys with the same object, it can be achieved by using a mutable object as a value.

For instance, you can make use of StringBuilder or implement a custom class. It’ll be more performant and easier than an approach with implementing your own map which extends HashMap and is able to track these groups of keys and triggers a series of updates for each call of put(), replace() or remove().

Solution with a custom mutable Container can look like this:

JavaScript

The Container class itself.

JavaScript

As I have already said, the alternative is to use a mutable class that is already provided by the JDK. The code is then almost the same:

JavaScript

Output (by both versions)

JavaScript
Advertisement