KyleKW KyleKW - 19 days ago 6
Java Question

Setting and Getting with Java Hashmaps

I'd like to create a HashMap with two String values. The first string value is of some "Mode" and the second string value is of some "State" for example:

"TRACK" mode is "DISABLED"

I would like to create a HashMap with multiple defined modes, with a "State" associated with each that changes from "ENABLED" or "DISABLED". This is what I have so far:

public class SystemModeStatus{

private Map<String String> map = new HashMap<String,String>(){
{
put("MODE_A", "STATE");
put("MODE_B", "STATE");
put("MODE_C", "STATE");
}
};

public SystemModeStatus(Map<String, String> m){
this.map = m;
}

public Map<String, String> getMap(){
return this.map;
}
}


Now what I would like to do is retrieve/set the "State" of each "Mode". However I can't seem to find the proper syntax.. am I approaching this correctly? Is there somethind I'm doing wrong that is complicating my process?

Thank you.

Answer

Firstly you should probably remove the getMap() method as you want to expose as few methods as possible on the internal map.

Then you can add methods to update the values in your map:

public void set(String mode, String status) {
    this.map.put(mode, status);
}

public String getStatus(String mode) {
    return this.map.get(mode);
}

More info here: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html

Comments