Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have 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; }
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
142 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...