Can I set enum start value in Java?

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

    whats about using this way:

    public enum HL_COLORS{
              YELLOW,
              ORANGE;
    
              public int getColorValue() {
                  switch (this) {
                case YELLOW:
                    return 0xffffff00;
                case ORANGE:
                    return 0xffffa500;    
                default://YELLOW
                    return 0xffffff00;
                }
              }
    }
    

    there is only one method ..

    you can use static method and pass the Enum as parameter like:

    public enum HL_COLORS{
              YELLOW,
              ORANGE;
    
              public static int getColorValue(HL_COLORS hl) {
                  switch (hl) {
                case YELLOW:
                    return 0xffffff00;
                case ORANGE:
                    return 0xffffa500;    
                default://YELLOW
                    return 0xffffff00;
                }
              }
    

    Note that these two ways use less memory and more process units .. I don't say this is the best way but its just another approach.

提交回复
热议问题