Skip to content
Advertisement

How can i create Enum in Java? [closed]

I already created Enum. But i cannot create new Enum. I wanna create and compare 2 Enums actually. The X value is coming from backend. It’s a dynamic value. I wanna make this;

EmployeeType type = new EmployeeType("X")

if (type == EmployeeType.X_PERSONALS) {
    Log.i("SAMPLE_TAG", "Yesss!")
}

public enum EmployeeType {
    X_PERSONALS("X"),
    Y_PERSONALS("Y"),
    Z_PERSONALS("Z");

    private final String text;

    EmployeeType(final String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

Advertisement

Answer

So what you are actually trying to achieve is to find the enum constant that has the same text. You can to that like this:

public enum EmployeeType {
    X_PERSONALS("X"),
    ///...and so on

    public static EmployeeType getByText(String x) {
        for(EmployeeType t:values()) {
            if(t.text.equals(x)){
                return t;
            }
        }
        return null;
    }
}

and then use the code like this:

EmployeeType type = EmployeeType.getByText("X");
if (type == EmployeeType.X_PERSONALS) {
    //and so on

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement