Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum values().length vs private field

Tags:

java

enums

People also ask

Does enum have length?

On an 8-bit processor, enums can be 16-bits wide. On a 32-bit processor they can be 32-bits wide or more or less. The GCC C compiler will allocate enough memory for an enum to hold any of the values that you have declared. So, if your code only uses values below 256, your enum should be 8 bits wide.

Should enum be private?

An enum is a type, not a data member. You should make it public if users of the class need to know about it; otherwise, make it private. A typical situation where users need to know about it is when it's used as the type of an argument to a public member function.

Can enum be private?

Enum FieldsThe enum constructor must be private . You cannot use public or protected constructors for a Java enum . If you do not specify an access modifier the enum constructor it will be implicitly private .

Should enum values be all caps?

Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.


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.


I would recommend using values().length. This is far more elegant and the performance overhead versus using a constant will be negligable. Also, you eliminate the risk of the constant ever becoming out of step with the actual length of the enumeration.


By storing the count you're violating the DRY principle, so unless you have a very good reason, you shouldn't.


Another approach is to use a constant initialized on top of the values() method.

public enum Colors {
    BLUE, GREEN, FUCHSIA;
    public static int length = Colors.values().length;
}

This way you have an automatically updated constant and still avoid that "values()" overhead.