使用枚举序数是一种好习惯吗? [英] Is it good practice to use ordinal of enum?

查看:36
本文介绍了使用枚举序数是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个枚举:

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.

或者做这样的事情更好:

Or is it better to do something like that:

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.EnumSetjava.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 and java.util.EnumMap.

首先 - 阅读手册(在本例中为 javadoc).

Firstly - read the manual (javadoc in this case).

其次 - 不要编写脆弱的代码.枚举值将来可能会发生变化,您的第二个代码示例清晰可维护.

Secondly - don't write brittle code. The enum values may change in future and your second code example is much more clear and maintainable.

如果在 PARENTGRANDPARENT 之间插入一个新的枚举值,你绝对不希望为未来制造问题.

You definitely don't want to create problems for the future if a new enum value is (say) inserted between PARENT and GRANDPARENT.

这篇关于使用枚举序数是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆