Reputation: 23
I have an enum and I would like to store some information with that enum. For example, this is what I have:
public enum MapName {
NONE,
CASTLE,
ISLANDS,
}
I want to be able to call a function like
MapName.NONE.get()
to get the value of the MapName. Ideally I would like to store multiple values. Is this possible, or do I have to create a separate class using if statements to return the proper variables?
Upvotes: 1
Views: 902
Reputation: 4805
Above answers are sufficient to understand enum.Now your requirement Enums are like constants you cannot store multiple values into an enum variable.If you want the enum name should be same but values should be different use different enum classes with same variables.
Upvotes: 0
Reputation: 1675
You can have an enum store values. See if this makes sense:
public enum MapName {
NONE("None"),
CASTLE("Castle"),
ISLANDS("Islands");
private String value;
MapName(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
Java enums have advanced functionality that can make them act similar to a static class with a set of static values. Using this you can add as many values per enum value as you want by simply adding more parameters!
You can use it like:
MapName.NONE.getValue(); //Returns "None"
Upvotes: 1
Reputation: 11867
enum
s in Java essentially are full classes. You can define variables, constructors (private only, though), methods, static methods, abstract methods, etc.:
public enum MapName {
NONE, CASTLE, ISLANDS;
private String name;
private MapName(String name) { this.name = name; }
public String getName() { return name; }
public static String getName(MapName instance) { return instance.getName(); }
}
You can also defined methods per-instance:
public enum MapName {
NONE {
@Override
public String getName() {
return "NONE";
}
},
CASTLE, // same thing for these other enums
ISLANDS;
public abstract String getName();
}
Upvotes: 1
Reputation: 31269
It's quite easy to associate extra information with an enum. Keep in mind that only one instance of each enum value exists, and hence also of each extra piece of information that you associate with it.
public enum MapName {
NONE("map1"), CASTLE("map2"), ISLANDS("map3");
private final String mapName;
private MapName(String mapName) {
this.mapName = mapName;
}
public String get() {
return mapName;
}
}
Upvotes: 1