Can I set enum start value in Java?

前端 未结 9 1686
长情又很酷
长情又很酷 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

    The ordinal() function returns the relative position of the identifier in the enum. You can use this to obtain automatic indexing with an offset, as with a C-style enum.

    Example:

    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);
        }
    };
    

    Gives the output:

    OPEN:  100
    CLOSE: 101
    OTHER: 102
    

    Edit: just realized this is very similar to ggrandes' answer, but I will leave it here because it is very clean and about as close as you can get to a C style enum.

提交回复
热议问题