enum.values() - is an order of returned enums deterministic

穿精又带淫゛_ 提交于 2019-11-28 04:01:58
GaryF

The Java language specification uses this explicit language:

@return an array containing the constants of this enum type, in the order they're declared [Source]

So, yes, they will be returned in declaration order. It's worth noting that the order might change over time if someone changes the class so be very careful about how you use this.

Yes, it is a guaranteed to return them in that order.

However you should avoid relying on that, and on the ordinal() value, since it can change after inserting new items, for example.

It is determined by the order your values are declared in. However, there is no guarantee that you (or someone else) won't reorder / insert / remove values in the future. So you shouldn't rely on the order.

Effective Java 2nd. Edition dedicates its Item 31 to a closely related topic: Use instance fields instead of ordinals:

Never derive a value associated with an enum from its ordinal; store it in an instance field instead.

The other answers are good, but don't comment on this:

"Is it a rule or it is not guaranteed to be not changed in the next Jdk releases?"

I don't believe that guarantees on future JDKs exist, so you shouldn't even worry about them. There would be no way to enforce them, future JDK leads might just decide to reneg on such guarantees. It's like the Westminster system of parliament: "No Parliament can bind a future parliament."

That said, the history of the JDK reveals excellent consistency. They don't make a lot of breaking changes, so you can be pretty confident that current specified (not just observed) behaviour will be preserved.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!