Can I set enum start value in Java?

前端 未结 9 1649
长情又很酷
长情又很酷 2020-11-30 18:09

I use the enum to make a few constants:

enum ids {OPEN, CLOSE};

the OPEN value is zero, but I want it as 100. Is it possible?

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 19:01

    I think you're confused from looking at C++ enumerators. Java enumerators are different.

    This would be the code if you are used to C/C++ enums:

    public class TestEnum {
    enum ids {
        OPEN,
        CLOSE,
        OTHER;
    
        public final int value = 100 + ordinal();
    };
    
    public static void main(String arg[]) {
        System.out.println("OPEN:  " + ids.OPEN.value);
        System.out.println("CLOSE: " + ids.CLOSE.value);
        System.out.println("OTHER: " + ids.OTHER.value);
    }
    };
    

提交回复
热议问题