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

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

问题描述

我有这样的枚举:

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 将在每次调用数组时创建一个新的数组副本.我有时会创建自己的 List(或设置或映射,无论我需要什么)以避免这种无意义的复制.我不会对其进行硬编码...如果您只需要大小,我会使用:

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;

最后.到评估时,所有值都将被初始化.这避免了其他答案中提出的 DRY 和不一致问题.

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天全站免登陆