KyleKW KyleKW - 25 days ago 10
Java Question

Setting indepedent states to Java enum values

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.

Answer

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.