枚举值()。长度与私有字段 [英] Enum values().length vs private field

查看:115
本文介绍了枚举值()。长度与私有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的枚举:

public enum Configuration {
    XML(1),
    XSLT(10),
    TXT(100),
    HTML(2),
    DB(20);

    private final int id;
    private Configuration(int id) {
        this.id = id;
    }
    public int getId() { return id; }
}

有时我需要检查枚举中有多少字段。什么是最好的解决方案?我应该使用一个方法values()。length?或者也许,我必须在枚举中创建常量字段:

Sometimes I need to check how many fields I have in enumeration. What is the best solution? Should I use a method "values().length"? Or maybe, I must create constant field in enumeration like this:

public enum Configuration {
    XML(1),
    XSLT(10),
    TXT(100),
    HTML(2),
    DB(20);

    private final int id;
    private Configuration(int id) {
        this.id = id;
    }
    public int getId() { return id; }

    public static final int Size = 5;
}

什么是最快,更优雅的解决方案?

What is the fastest and more elegant solution?

推荐答案

使用 values()。length 将在每次调用该数组时创建一个新的副本。我有时会创建我自己的列表(或设置或映射,无论我需要什么),以避免这种无意义的复制。我不会硬编码,但如果您只需要大小,我只需使用:

Using values().length will create a new copy of the array every time you call it. I sometimes create my own List (or set, or map, whatever I need) to avoid this pointless copying. I wouldn't hard-code it though... if you only need the size, I'd just use:

private static final int size = Configuration.values().length;

到底。在被评估的时候,所有的值都将被初始化。这避免了其他答案中提出的干扰和不一致问题。

at the end. By the time that is evaluated, all the values will have been initialized. This avoids the DRY and inconsistency concerns raised in other answers.

当然,这是一个微型优化本身...但是最后一个更简单的代码到最后,IMO。从其他地方调用 values()。length 并不表示你感兴趣的东西,这只是枚举的大小 - 这个事实你通过一系列值得到的东西是偶然和分心的,IMO。

Of course, this is a bit of a micro-optimisation in itself... but one which ends up with simpler code in the end, IMO. Calling values().length from elsewhere doesn't express what you're interested in, which is just the size of the enum - the fact that you get at it through an array of values is incidental and distracting, IMO.

使用 values()是使用 EnumSet.allOf()。size()对于小枚举将是相当便宜 - 但是再次,它不像只有一个 size 字段。

An alternative to using values() is to use EnumSet.allOf().size() which for small enums will be pretty cheap - but again, it's not as readable as just having a size field.

这篇关于枚举值()。长度与私有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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