enum.values() - 是返回枚举确定性的顺序
我有一个枚举 SOME_ENUM
:
public enum SOME_ENUM {
EN_ONE,
EN_TWO,
EN_THREE;
}
SOME_ENUM.values()
始终按枚举声明的顺序返回枚举: EN_ONE、EN_TWO、EN_THREE
?这是一个规则还是不保证在下一个 JDK 版本中不会更改?
I have a enum SOME_ENUM
:
public enum SOME_ENUM {
EN_ONE,
EN_TWO,
EN_THREE;
}
Will SOME_ENUM.values()
always return the enums in the order of enum declarations:EN_ONE, EN_TWO, EN_THREE
? Is it a rule or it is not guaranteed to be not changed in the next JDK releases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Java 语言规范使用这种显式语言:
所以,是的,它们将按声明顺序返回。值得注意的是,如果有人更改了类,顺序可能会随着时间的推移而改变,所以要非常小心如何使用它。
The Java language specification uses this explicit language:
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.
是的,保证按顺序归还它们。
但是,您应该避免依赖它以及
ordinal()
值,因为它可能会在插入新项目后发生变化。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.它由您声明值的顺序决定。但是,不能保证您(或其他人)将来不会重新排序/插入/删除值。所以你不应该依赖命令。
有效的Java 2。版本将其第 31 条专门用于一个密切相关的主题:使用实例字段而不是序数:
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:
其他答案都很好,但不评论这个:
我不相信对未来 JDK 的保证存在,所以你甚至不应该担心它们。没有办法强制执行它们,未来的 JDK 领导可能会决定违背这样的保证。这就像威斯敏斯特议会制度:“没有议会可以约束未来的议会。”
也就是说,JDK 的历史显示出出色的一致性,它们没有做出很多重大更改,因此您可以对当前指定的内容非常有信心。 (不仅仅是观察到的)行为将被保留。
The other answers are good, but don't comment on this:
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.
添加到GaryF 答案之上。
是的,订单由 Java 保证。然而......
混淆可能会破坏它。所以要非常小心
To add on top of GaryF answer.
Yes the order is guaranty by the Java. However...
Obfuscation can break it. So be very carful with it