Gettin枚举类型可能无法实例化异常

Zio*_*ion 1 java enums instantiation

我得到RuntimeException

枚举类型可能无法实例化

我不知道为什么.我想要的是用一个整数值来标识一年,就像我有9所以其他方法的年份是2006年.代码:

public class P21Make {

    enum Catalog {
        year2005(9),year2006(12),year2007(15),year2008(18),
        year2009(21),year2010(23),year2011(25),year2012(28),
        year2013(31),year2014(33),year2015(36),year2016(39),
        year2017(42),year2018(45),year2019(48),year2020(51);

        private int id;    

        Catalog(int c){
            this.id=c;
        }
    }

    public P21Make() {
        Catalog c = new Catalog(9);   // The Exception 
    }
}
Run Code Online (Sandbox Code Playgroud)

sol*_*4me 6

你无法像这样实例化枚举.你有2个可能性

1.Catalog c = Catalog.year2005;
Run Code Online (Sandbox Code Playgroud)

2.通过添加一个可以根据代码返回枚举的方法(整数值),在枚举中进行以下更改.例如

   enum Catalog {
      year2005(9),year2006(12),year2007(15),year2008(18),
      year2009(21),year2010(23),year2011(25),year2012(28),
      year2013(31),year2014(33),year2015(36),year2016(39),
      year2017(42),year2018(45),year2019(48),year2020(51);
      private int id;

      Catalog(int c){
         this.id=c;
      }


      static Map<Integer, Catalog> map = new HashMap<>();

      static {
         for (Catalog catalog : Catalog.values()) {
            map.put(catalog.id, catalog);
         }
      }

      public static Catalog getByCode(int code) {
         return map.get(code);
      }
   }
Run Code Online (Sandbox Code Playgroud)

然后像这样分配

Catalog c = Catalog.getByCode(9);
Run Code Online (Sandbox Code Playgroud)