[英]HashMap<String, Object> How to replace 1 value of the Object?
Map<String, Data> map = new HashMap<String,Data>();
map.put("jan", new Data("RED","M4A1",5,0,0));
How can I change the value RED of the Data object?, without getting all the information out of the map with the key and putting it back in, like this:如何更改 Data 对象的值 RED?,而无需使用键从地图中取出所有信息并将其放回原处,如下所示:
map.put("jan" new Data("Blue",
map.get("jan").Brand,
map.get("jan").Storage,
map.get("jan").Sold,
map.get("jan").Bought));
So how can i change 1 value of the Data Object instead of redo them all?那么如何更改数据对象的 1 个值而不是全部重做?
It depends on whether Data
is mutable.这取决于Data
是否可变。 For example, you may be able to write:例如,您可以编写:
Data data = map.get("jan");
data.setColor("Blue");
Don't forget that the map only contains a reference to the object, so if you change the data within the object, that change will be seen if someone fetches the reference from the map later.不要忘记地图只包含对对象的引用,因此如果您更改对象内的数据,那么如果稍后有人从地图中获取引用,则会看到该更改。
Or if it's immutable, it could potentially have a withColor
method, so you could write:或者如果它是不可变的,它可能有一个withColor
方法,所以你可以写:
Data data = map.get("jan");
map.put("jan", data.withColor("Blue"));
Without knowing more about your Data
type (which I hope isn't the real name of your class) it's hard to say any more.如果不了解更多关于您的Data
类型(我希望它不是您班级的真实名称),就很难再多说了。
(I also hope your class doesn't really have Pascal-cased fields, and I hope those fields are private, but that's a different matter...) (我也希望你的班级没有真正的 Pascal-cased 字段,我希望这些字段是私有的,但那是另一回事......)
Assuming Data
is mutable you can set the "RED"
field:假设Data
是可变的,您可以设置"RED"
字段:
Map map = new HashMap();
map.put("jan", new Data("RED","M4A1",5,0,0));
// Later...
map.get("jan").setColor("BLUE");
If Data
isn't mutable, then your only option is to put
the new value as you have it written.如果Data
不可变,那么您唯一的选择是put
新值按写入的方式put
。
Assuming Data
has a setter
for the color
property:假设Data
有一个color
属性的setter
:
public class Data {
private String color;
public void setColor(String color) {
this.color = color;
}
}
You can just get
the required Data
object and set its property:您可以get
所需的Data
对象并设置其属性:
Data data = map.get("jan");
data.setColor("blue");
Add appropriate setter to your Data
class, eg将适当的 setter 添加到您的Data
类,例如
class Data {
setColor(String color){...}
}
map.get("jan").setColor("BLUE");
Please find the code snippet:请找到代码片段:
Map<String, Data> map = new HashMap<String,Data>();
public class Data{
private String color;
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return this.color;
}
publicData(String color){
this.setColor(color);
}
}
map.put("jan", new Data("RED","M4A1",5,0,0));
Now you may do like this:现在你可以这样做:
Data data = map.get("jan");
data.setColor("black");
This will work.这将起作用。
Here the class Data contains only one field ie color.这里的类 Data 只包含一个字段,即颜色。 You can add more fields.您可以添加更多字段。 Thanks谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.