使用枚举序号是一种好习惯吗? [英] Is it good practice to use ordinal of enum?
问题描述
我有一个枚举:
public enum Persons {
CHILD,
PARENT,
GRANDPARENT;
}
使用ordinal()
方法检查枚举成员之间的层次结构"是否存在问题?我的意思是-使用它时,除了冗长之外,还有什么缺点吗?将来有人可能会意外更改顺序.
Is there any problem with using ordinal()
method to check "hierarchy" between enum members? I mean - is there any disadvantages when using it excluding verbosity, when somebody can change accidentally order in future.
或者做这样的事更好:
public enum Persons {
CHILD(0),
PARENT(1),
GRANDPARENT(2);
private Integer hierarchy;
private Persons(final Integer hierarchy) {
this.hierarchy = hierarchy;
}
public Integer getHierarchy() {
return hierarchy;
}
}
推荐答案
TLDR:不,您不应该!
如果您在Enum.java
中为ordinal
方法引用了Javadoc:
If you refer to the javadoc for ordinal
method in Enum.java
:
大多数程序员都不会使用此方法.它是 设计供基于枚举的复杂数据结构使用,例如 为
java.util.EnumSet
和java.util.EnumMap
.
Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as
java.util.EnumSet
andjava.util.EnumMap
.
首先-阅读手册(在这种情况下为javadoc).
Firstly - read the manual (javadoc in this case).
其次-不要编写易碎的代码.枚举值将来可能会更改,您的第二个代码示例更容易理解 clear 和 maintainable .
Secondly - don't write brittle code. The enum values may change in future and your second code example is much more clear and maintainable.
如果在PARENT
和GRANDPARENT
之间插入(例如)新的枚举值,则您绝对不希望为将来造成麻烦.
You definitely don't want to create problems for the future if a new enum value is (say) inserted between PARENT
and GRANDPARENT
.
这篇关于使用枚举序号是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!