This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Start java enum ordinal at 1 instead of 0

 
Theodore David Williams
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way that I can start the ordinal value of an enum @ 1 instead of the default of 0?

i.e.


That does not compile. I know enums are classes not ints so looking at the enum constructor I could use Enum(Sting name, int ordinal), but that would require me to name each enum and I would lose the nicety of having my enum name default to the string value.

Any ideas?

Thanks
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64833
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm curious, why do you care? It's usually an implementation detail that we don't even need to know about.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you really need the enums to have a value that starts at 1, why not create another method that simply returns ordinal() + 1?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15280
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that using the ordinal values of an enum isn't really "safe" with regard to maintenance of your code, because you're tightly tying your source code to values that might have meaning to the business logic.

Suppose that you're storing ordinal values in a database. Someday you edit your enum and you add a new constant.

Note that the ordinal number of the status CLOSED will have changed, because you added a new constant (BLOCKED) in between. Because you tied your source code so tightly to the data values, the old values in your database will no longer be valid.

It's better to add your own, explicit codes to the enum, like this:

Now you can add a status BLOCKED without changing the code of the status CLOSED. Besides that, the codes are explicit in your source code, so that you don't have to guess what a code that you see in the database means.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic