Question

I need to create an enumeration like this:

public enum STYLE {
ELEMENT1(0), A/R (2)
//Staff
};

But Java does not permit this. Is there any solution? Thanks

Was it helpful?

Solution 3

Enumeration in java is just a compile time syntactic sugar. Actually enum is just a class and enum member is just as public final static field of this class. Each field has name that must follow certain rules. For example name cannot contain special characters that mean something special in the language. For example / cannot be used as a part of name.

You can call it A_R if you want.

If however you want additionally to be able to extract string A/R from enum member A_R you can define method that returns it, e.g.

public enum STYLE {
    ELEMENT1(0), 
    A_R (2) {
        @Override
        public String printableName() {
            return "A_R";
        } 
    };

    public String printableName() {
        return name();
    } 
}

OTHER TIPS

You cannot use / to name a Java identifier. You can have a look at the §JLS 3.8 to see what all special characters are allowed in naming of a Java identifier.

For your scenario, you can use an enum which looks like this.

enum STYLE {
    ELEMENT1(0, "ELEMENT1"), A_R(2, "A/R");

    private int code;
    private String name;

    private STYLE(int code, String name) {
        this.code = code;
        this.name = name;
    }
    // Other methods.
}

/ cannot be used in the name. If your A/R constant denotes "A or R", you can rename it to A_OR_R.

Edit:

If you need to compare it to a String equal to "A/R", you can override the toString() method in the constant.

public enum Style {
    A_OR_R(2) {
        public @Override String toString() {
            return "A/R";
        }
    }, ELEMENT1(0);
}

Then

String test = "A/R";
boolean isEqual = test.equals(style.A_OR_R.toString());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top