简体   繁体   English

我可以在 java 中使用变量值创建 hashmap 吗?

[英]Can i create a hashmap in java with variable values?

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. 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?假设字符串是左前、右前等,integer 是那个轮子的速度,随着时间的推移而变化。我可以做这样的事情,还是我必须在 Integer 换档器时重新声明每个条目?

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.首先, HashMap中的值就是:值。 Java values don't change spontaneously. Java 值不会自发改变。

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 .然后,代表speed变量的 object 需要为代表baseSpeedgeargearRatio的对象上的“更改”事件注册一个事件侦听器。 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.speed object 获得这些事件之一时,它需要重新计算其值,然后通知任何其他正在侦听其上的“更改”事件的对象。

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. Java Swing 事件通知框架就是做这种事情的。 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.我不提倡将它用于与 Swing 无关的事件,但您可以将其用作如何执行此类操作的示例。 Java Bean notifications are another example. Java Bean 通知是另一个示例。


However, I suspect that this is an XY problem, and that there is likely be a better (simpler) way to solve it.但是,我怀疑这是一个 XY 问题,并且可能有更好(更简单)的方法来解决它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM