Enum values().length vs private field

后端 未结 4 1700
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 13:12

I have enumeration like this:

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

    private final int id;
    pri         


        
4条回答
  •  庸人自扰
    2020-12-08 13:43

    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.

    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.

    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.

提交回复
热议问题