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
.
HashMap<String, Integer> map = new HashMap<>(); map.put("x", 0); map.put("y", 0); //I now somehow want to link the value of x so its dependent on y System.out.println(map.get("x")); //Should return 0 map.put("y", 10); System.out.println(map.get("x")); //Should return 10 now
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:
HashMap<String, Container<Integer>> map = new HashMap<>(); Container<Integer> commonValue = new Container<>(0); map.put("x", commonValue); map.put("y", commonValue); System.out.println("Value for 'x': " + map.get("x")); System.out.println("Value for 'y': " + map.get("y")); commonValue.setValue(10); System.out.println("Value for 'x': " + map.get("x")); System.out.println("Value for 'y': " + map.get("y"));
The Container
class itself.
public class Container<T> { private T value; public Container(T value) { this.value = value; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } }
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:
HashMap<String, StringBuilder> map = new HashMap<>(); StringBuilder commonValue = new StringBuilder("0"); map.put("x", commonValue); map.put("y", commonValue); System.out.println("Value for 'x': " + map.get("x")); System.out.println("Value for 'y': " + map.get("y")); commonValue.replace(0, commonValue.length(), "10"); System.out.println("Value for 'x': " + map.get("x")); System.out.println("Value for 'y': " + map.get("y"));
Output (by both versions)
Value for 'x': 0 Value for 'y': 0 Value for 'x': 10 Value for 'y': 10