简体   繁体   中英

get enum .values()[] or create Enum array?

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?

If you do Compass.values(); the order that your values are returned in will be the order in which they are written in the Enum class. If your code is reliant on the order of the contents of the array, it is better to create your own array as in your example, and control the order at the point you need it.

If you just want to get hold of a specific value of this enum, such as NORTH, you can just write Compass.NORTH.name(); rather than using an array at all.

To obtain the name of one of the enum values directly, without using an array, you can do this:

Compass.NORTH.name();

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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM