开发者

Using integer in enumerated type

I am trying to declare this enum:

public enum Month {
    1, 2, 3, 4, 5 , 6, 7, 8, 9, 10, 11, 12;
}

But when I try to compile it doesn't work. Is this beca开发者_StackOverflow中文版use the constants are integers?


Yes - the values of an enum have to be valid identifiers. They're basically static fields after all - you're effectively trying to declare:

public static Month 1 = new Month();

which obviously isn't valid.

See the Java Language Specification section 8.9 for details, but in particular this production:

EnumConstant:
Annotations Identifier Argumentsopt ClassBodyopt


public enum Month {
  JANUARY(1),
  FEBRUARY(2),
  ...
  DECEMBER(12);

  private int number;

  private Month(int number) {
    this.number = number;
  }

  public int getNumber() {
    return number;
  }
}


As @Jon Skeet said, you are not going to be able to use integers as identifiers in your code. The closest thing that you can do is associate a integer value to your constants:

public enum Month {
   ONE(1),
   TWO(2);

   private final int number;

   private Month(int number) {
     this.number = number;
   }

   public int getNumber() { return number; }
}

so that you can do something like this:

Month.ONE.getNumber()

not sure if this suits your needs though.


You use this horrible work around.

public enum Month {
    _1, _2, _3, _4, _5 , _6, _7, _8, _9, _10, _11, _12;
}

However another approach is to use name and ordinal() for numbers.

public enum Month {
    None, 
    January, February, March, April, May, June, 
    July, August, September, October, November, December
}

Month month = Month.January;
int num = month.ordinal(); // == 1
Month month2 = Month.values()[num]; // == January.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜