0

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 ?

5
  • yeah. that is possible Commented Aug 21, 2022 at 9:33
  • Can you provide the "whole picture"? Where do these variables baseSpeed, gear and gearRatio come from? Commented Aug 21, 2022 at 9:42
  • Sidenote: in Java, type String starts from a capital letter. Commented Aug 21, 2022 at 9:44
  • 1
    "hashmap that stores the speed of every wheel at a given time" - So what should be the Key of the Map? Commented Aug 21, 2022 at 10:00
  • This declaration would not compile, and it doesn't explain how map value is intended to be provided private int Integer= baseSpeed +gear*gearRatio; Commented Aug 21, 2022 at 10:00

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.