Re: How to store an enum value as a corresponding integer?
On 2/12/2011 6:35 AM, Robin Wenger wrote:
Internally in a class I would like to store a value as integer value.
Why? I suppose that if you have many millions of instances of
the class, and you're using a 64-bit JVM where references take twice
as much memory as ints, and if heap profiling shows that saving four
bytes per mycontainer instance would amount to a useful savings, then
maybe there might be a reason to do this. But unless all those hold
(and you've made actual measurements to see that they do), this smacks
of premature optimization, a.k.a. the root of all evil. Still...
From outside of the class this value should be accessible as enumeration.
I am thinking about something like:
pubic class mycontainer {
....
private int myvalue;
public enum weekday { monday, tuesday, wednesday };
public weekday getcurrentweekday() {
return(positioninlist(myvalue)); }
return weekday.values()[myvalue];
Note that this will create a brand-new array each time it's called
(so an outside caller can't meddle with the internals of the enums).
Since you wouldn't be playing these games unless you expected a very
large number of instances (and, presumably, calls), you might do better
to instantiate one `static final weekday[] VALUES = weekday.values();'
when the mycontainer class is first loaded.
public void setcurrentweekday(weekday) {
myvalue=positioninlist(weekday);
myvalue = weekday.ordinal();
}
}
Two observations: First, it will do you good to follow the usual
naming conventions for Java.
class mycontainer -> class MyContainer
public enum weekday -> public enum Weekday // or WeekDay
monday -> MONDAY
getcurrentweekday -> getCurrentWeekday // or ...WeekDay
.... and so on. Your code will be easier for other people to read
(If yOU thInk lEttEr cAsE dOEsn't AffEct rEAdAbIlIty, thAnk AgAIn),
and you'll find it'll also be easier for you yourself to read.
Second, as mentioned above, this whole business is probably a
poor idea unless you've already been backed into a desperate corner.
Don't go into that corner of your own free will.
--
Eric Sosman
esosman@ieee-dot-org.invalid