Reputation: 300
I'm fairly new to Java Enums and I'm currently trying to implement an Enum list where each of the values have some True/False value associated with each. My enum list looks like this essentially:
public enum SomeEnum{
A("A"),
B("B"),
C("C"),
D("D");
private String name;
private SomeEnum(String name){
this.name = name;
}
}
However, I want each enum value to have a "TRUE" or "FALSE" associated with it. Is this plausible with Java enums? Or would I need to approach it without using enums. Ultimately I'd like to have some setter/getter method to set and get each status independently.
Thank you!
EDIT: Sorry for being confusing, I wasn't exactly clear on what I wanted do do. I'm creating a message set for DDS and would like to create a message set for a panel of status messages that show either TRUE or FALSE respectively and can be changed. I figured I could somehow do this using enums instead of creating a separate instance of each variable.
Upvotes: 3
Views: 2107
Reputation: 7808
The answer is yes and it is simple to do.
public enum SomeEnum{
A(true),
B(false),
C(true),
D(false);
private boolean flag;
private SomeEnum(boolean flag){
this.flag = flag;
}
public boolean getFlag() {
return flag;
}
}
Also you don't need to do name variable since enum already has a method called name()
that returns you a String representing the name of your instance. If you want the String to be dfferent just override method toString()
and use it to get a String that is not the same as your enum instance name
Upvotes: 0
Reputation: 30568
Short answer: depends on your use case. It is perfectly plausible to have something like this:
public enum SomeEnum{
A(true),
B(false),
C(true),
D(false);
private boolean myBool;
private SomeEnum(boolean myBool){
this.myBool = myBool;
}
public boolean geMyBool() {
return myBool;
}
}
Don't use the name
as the name of your field though because the String
representation of the name of an enum value (A
, B
etc) is used as a name
of all enum
values in Java. So for example SomeEnum.A.getName()
equals "A". This functionality is built in for all enums.
Please also note that if you set the value of myBool
it will confuse the users of your enum because the runtime state will be inconsistent with the value present in the source code.
Upvotes: 4
Reputation: 7207
You are near to the solution, just add a new param to the constructor
public enum SomeEnum{
A("A", true),
B("B", false),
C("C", true),
D("D", false);
private String name;
private boolean flag;
private SomeEnum(String name, boolean flag){
this.name = name;
this.flag = flag;
}
}
Upvotes: 0
Reputation: 2495
public enum SomeEnum{
A("A", true),
B("B", false),
C("C", false),
D("D", true);
private String name;
private boolean isImportant;
private SomeEnum(String name, boolean isImportant){
this.name = name;
this.isImportant = isImportant;
}
}
Upvotes: 0