I have to use a switch to get the values of a enum. The enum is this one:
public enum Compass { NORTH, SOUTH, EAST, WEST; }
And I did this (in another Class outside the enum):
Compass.values()[0].name()
But the book says that the way to do it is:
Compass[] comp = { Compass.NORTH, Compass. SOUTH, Compass.EAST, Compass.WEST }
comp[0].name();
Is any of them better than the other? I mean, is more stable creating a Enum “object” or something?
To obtain the name of one of the enum values directly, without using an array, you can do this:
The array returned by
Compass.values()is in the order the enums are declared, so there is no benefit creating an array separately unless you don’t like the declared order (and can’t change it) or you are concerned that someone else will alter the order (e.g. insert a new value) and break your code.Generally, though, you want to avoid duplication because that means maintaining two things instead of one and it’s easy for things to get out of sync. If someone added NORTH_EAST, SOUTH_WEST etc. you would have to remember to update your array to cater for these values or find that perhaps your code doesn’t work in certain situations.