Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add slash to an enumeration in Java

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

like image 614
Houssem Badri Avatar asked Nov 30 '22 20:11

Houssem Badri


2 Answers

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.
}
like image 179
Rahul Avatar answered Dec 04 '22 18:12

Rahul


/ 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());
like image 45
Konstantin Yovkov Avatar answered Dec 04 '22 17:12

Konstantin Yovkov