小编典典

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

java

我正在收到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 
    }
}

阅读 340

收藏
2020-11-26

共1个答案

小编典典

您不能像这样实例化枚举。您有2种可能性

1.Catalog c = Catalog.year2005;

2.通过添加可以根据code(integer value)返回枚举的方法,对枚举进行以下更改。例如

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

然后像这样分配

Catalog c = Catalog.getByCode(9);
2020-11-26