aspose file tools*
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


Win a copy of Spring in Action this week in the Spring forum!
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
Author

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?

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

Joined: Jan 10, 2002
Posts: 61419
    
  67

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] [Bear's FrontMan] [About Bear] [Books by Bear]
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19719
    
  20

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14268
    
  21

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
 
jQuery in Action, 2nd edition
 
subject: Start java enum ordinal at 1 instead of 0