File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Start java enum ordinal at 1 instead of 0 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Start java enum ordinal at 1 instead of 0" Watch "Start java enum ordinal at 1 instead of 0" New topic

Start java enum ordinal at 1 instead of 0

Theodore David Williams
Ranch Hand

Joined: Dec 21, 2009
Posts: 102
Is there a way that I can start the ordinal value of an enum @ 1 instead of the default of 0?


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?

Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63865

I'm curious, why do you care? It's usually an implementation detail that we don't even need to know about.

[Asking smart questions] [About Bear] [Books by Bear]
Rob Spoor

Joined: Oct 27, 2005
Posts: 20275

If you really need the enums to have a value that starts at 1, why not create another method that simply returns ordinal() + 1?

How To Ask Questions How To Answer Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15092

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.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
I agree. Here's the link:
subject: Start java enum ordinal at 1 instead of 0
jQuery in Action, 3rd edition