user1621988
user1621988

Reputation: 4355

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:

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?

Upvotes: 9

Views: 24157

Answers (5)

Shreyos Adikari
Shreyos Adikari

Reputation: 12764

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 i.e. color. You can add more fields. Thanks

Upvotes: 0

Brian
Brian

Reputation: 17329

Assuming Data is mutable you can set the "RED" field:

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.

Upvotes: 4

AlexR
AlexR

Reputation: 115418

Add appropriate setter to your Data class, e.g.

class Data {
    setColor(String color){...}
}


map.get("jan").setColor("BLUE");

Upvotes: 2

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91379

Assuming Data has a setter for the color property:

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:

Data data = map.get("jan");
data.setColor("blue");

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504122

It depends on whether Data is mutable. 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:

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.

(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...)

Upvotes: 12

Related Questions