• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Start java enum ordinal at 1 instead of 0  RSS feed

 
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
 
Marshal
Posts: 67162
169
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.
 
Sheriff
Posts: 21463
97
Chrome Eclipse IDE Java Spring Ubuntu VI Editor 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?
 
Java Cowboy
Posts: 16084
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!