Using an integer in an enumerated type

I am trying to declare this listing:

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

But when I try to compile, this will not work. Is it because constants are integers?

+4
source share
4 answers

Yes - enumeration values ​​must be valid identifiers. After all, these are mostly static fields - you are really trying to declare:

 public static Month 1 = new Month(); 

which is obviously invalid.

For more information, see "Java Language Specification" 8.9 , but in particular this:

EnumConstant:
Annotations Identifier Arguments opt ClassBody opt

+6
source
 public enum Month { JANUARY(1), FEBRUARY(2), ... DECEMBER(12); private int number; private Month(int number) { this.number = number; } public int getNumber() { return number; } } 
+2
source

As @Jon Skeet said, you cannot use integers as code identifiers. The closest you can do is associate an integer value with 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 you can do something like this:

 Month.ONE.getNumber() 

not sure if this fits your needs.

+1
source

You use this terrible job.

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

However, another approach is to use a name and serial number () 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
source

All Articles