1

I have a class that defines a Map<Integer, String> commands variable, wherein the Integer is the command number and the String is the name for it.

The reason I didn't make this an enum is that I was under the impression that values in an enum have to be sequential, id est increment by one (but the command keys don't). Having looked at the below code, I'm of the impression that this assumption of mine is wrong:

public enum HttpStatusCode {
 OK(200), NO_CONTENT(204), NOT_FOUND(404) /* .... */ ;
}

Do the values in an enum have to increment by one for each value or are gaps in value allowed?

Agi Hammerthief
  • 2,114
  • 1
  • 22
  • 38
  • https://stackoverflow.com/questions/5372855/can-i-specify-ordinal-for-enum-in-java maybe this will help also – Kacper Wolkowski May 03 '18 at 12:51
  • 1
    If you've already got a map, you could also just use the enum as the key and forget about values completely. – biziclop May 03 '18 at 12:52
  • @KacperWolkowski Thanks. I had looked at that example/answer prior to posting. However, it shows the values being set in sequence. (It also starts at `1`, which led me to believe that the first ordinal in an enum is `1`, not `0`.) – Agi Hammerthief May 03 '18 at 12:55
  • In Java, enums are fully functional classes, you can give them as many fields as you want to (as seen in the answer from @daniu). In general you shouldn't care about or use the value of `ordinal()` for anything. – biziclop May 03 '18 at 13:11
  • s/functional/functioning/g – biziclop May 03 '18 at 13:57

1 Answers1

3

Gaps are allowed, in fact you can define an actual constructor.

public enum HttpStatusCode {
   OK(200), NO_CONTENT(204), NOT_FOUND(404);
   private int status;
   private HttpStatusCode(int st) { status = st; }
   public int getStatus() { return status; }       
}

You still get incremental values by the ordinal().

daniu
  • 14,137
  • 4
  • 32
  • 53