Home > Software design >  Can i create a hashmap in java with variable values?
Can i create a hashmap in java with variable values?

Time:08-22

I want to create an object in java that includes a hashmap.Let's say that my object is a car and i want to create a hashmap that stores the speed of every wheel at a given time. What i mean is this :

private int baseSpeed=60;
private int gearRatio=5;
private int  gear; 
private int Integer= baseSpeed  gear*gearRatio;
private HashMap<String, Integer> carSpeed = new HashMap<>();
 

Let's say that string is frontLeft,frontRight etc and integer is the speed of that wheel,that changes over time.Can i do something like this, or do i have to redeclare each entry whenever Integer gear changer ?

CodePudding user response:

It I understand what you are saying correctly ... the answer is that it is not possible unless you build a lot of extra infrastructure.

First, the value in a HashMap are just that: values. Java values don't change spontaneously.

If you want something to change in response to (say) something else changing, you need to implement it on top of an event notification mechanism of some kind. So suppose we had

speed = baseSpeed   gear * gearRatio;

what we would need is an event that means "object value has changed". Then the object that represents the speed variable would need to register an event listener for the "changed" event on the objects that represent the baseSpeed, gear and gearRatio. When the speed object gets one of these events, it would need to recalculate its value, and then notify any other objects that are listening for "changed" events on it.

It is complicated, but do-able. And you will need to do most of the work for yourself, or find a 3rd-party framework that does this. The Java Swing event notification framework does this kind of thing. I wouldn't advocate using it for events that are not Swing related, but you can use it as an example of how to do this kind of thing. Java Bean notifications are another example.


However, I suspect that this is an XY problem, and that there is likely be a better (simpler) way to solve it.

  • Related