Can I set enum start value in Java?

前端 未结 9 1677
长情又很酷
长情又很酷 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 18:48

    @scottf

    An enum is like a Singleton. The JVM creates the instance.

    If you would create it by yourself with classes it could be look like that

    public static class MyEnum {
    
        final public static MyEnum ONE;
        final public static MyEnum TWO;
    
        static {
            ONE = new MyEnum("1");
            TWO = new MyEnum("2");
        }
    
        final String enumValue;
    
        private MyEnum(String value){
            enumValue = value;    
        }
    
        @Override
        public String toString(){
            return enumValue;
        }
    
    
    }
    

    And could be used like that:

    public class HelloWorld{
    
       public static class MyEnum {
    
           final public static MyEnum ONE;
           final public static MyEnum TWO;
    
           static {
              ONE = new MyEnum("1");
              TWO = new MyEnum("2");
           }
    
           final String enumValue;
    
           private MyEnum(String value){
               enumValue = value;    
           }
    
           @Override
           public String toString(){
               return enumValue;
           }
    
    
       }
    
        public static void main(String []args){
    
           System.out.println(MyEnum.ONE);
           System.out.println(MyEnum.TWO);
    
           System.out.println(MyEnum.ONE == MyEnum.ONE);
    
           System.out.println("Hello World");
        }
    }
    

提交回复
热议问题