Re: Java 5.0 Enum: why not valueOf(int ordinal)?
- From: Wibble <Wibble@xxxxxxxxxxxxxx>
- Date: Fri, 18 Nov 2005 19:36:47 -0500
diegomrosa wrote:
If you had stored information on the enum based on the ordinal (say writing ordinal values to a file for later rereading) then these values would correspond to the wrong enums when reloaded. On the other hand, had you used the string values, all would be well. If you *know* that your enum is never going to change, using the ordinal may be suitable. If you do have to add values later, just make sure to put them at the end.
maybe the right question would be: "how to safely/efficiently store enum values?". Well, I dont know about the rest of you, but I need to persist enum values all the time!
The obvious way to store an enum value seems to be using its ordinal (at least to me!). Storing the string values would be a lot more expensive and not a bit more secure. You are right in saying that storing the ordinal could be dangerous in case you change the enum order. However, storing the string value would prohibit the user changing the name of the enum constants. Both cases seem remote to me, but I would consider changing a enum value name even more common than changing its order. That is why my surprise that class Enum has a method to convert a string into an enum but not an equivalent to convert an ordinal into an enum.
Ok, I can write a method somewhere to convert an ordinal into an enum, but where should I put it?!? Well, the Enum class seems to be the obvious choice.
If you are sure your enum won't change, or that values will only be added to the end, then a static method such as:
enum Ints { ZERO,ONE,TWO,THREE,FOUR;
public static Ints fromOrd(int i) { if (i < 0 || i >= Ints.values().length) { throw IndexOutOfBoundsException("Invalid ordinal"); } return Ints.values()[i]; } }
this means I have to duplicate this code on every Enum. Frustrating!
might work. Alternatively you can build you own ordinal system that can use values you define, although it's a bit of a PITA:
enum Ints { ZERO(0), ONE(1), TWO(2), THREE(3), FOUR(4);
private final int _ord;
Ints(int i) { _ord = i; }
int getOrd() { return _ord; } }
More frustrating!
Diego
Heinz wrote a good article on this. If you haven't read his newsletters yet, there very good.
http://www.javaspecialists.co.za/archive/Issue113.html .
- References:
- Java 5.0 Enum: why not valueOf(int ordinal)?
- From: diegomrosa
- Re: Java 5.0 Enum: why not valueOf(int ordinal)?
- From: David Hume
- Re: Java 5.0 Enum: why not valueOf(int ordinal)?
- From: diegomrosa
- Java 5.0 Enum: why not valueOf(int ordinal)?
- Prev by Date: Re: Dealing with packages UNIX
- Next by Date: Re: File util API to move files accross partitions/filesystems
- Previous by thread: Re: Java 5.0 Enum: why not valueOf(int ordinal)?
- Next by thread: Re: Java 5.0 Enum: why not valueOf(int ordinal)?
- Index(es):
Relevant Pages
|