Enum values ​​(). Length vs private field

I have an 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 an enumeration. What is the best solution? Should I use the "values ​​(). Length" method? Or maybe I should create a constant field in the listing as follows:

 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 most elegant solution?

+49
java enums
Nov 16 '09 at 11:49
source share
4 answers

Using values().length will create a new copy of the array every time you call it. Sometimes I create my own List (or install, or the map that I need) to avoid this pointless copying. I would not hardcode it, though ... if you only need size, I would just use:

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

in the end. By the time of evaluation, all values ​​will be initialized. This avoids the DRY problems and inconsistencies that arise in other answers.

Of course, this is a bit of micro-optimization in itself ... but one of which ends with a simpler code at the end, IMO. Calling values().length from another source doesn't express what interests you, it's just the size of the enumeration - the fact that you get it through an array of values ​​is random and distracting, IMO.

An alternative to using values() is to use EnumSet.allOf().size() , which for small enumerations will be quite cheap - but again, it is not as readable as it simply has a size field.

+86
Nov 16 '09 at 11:54
source share

I would recommend using values().length . This is much more elegant, and overhead performance compared to using a constant will be careless. In addition, you eliminate the risk that the constant constantly fails with the actual listing length.

+9
Nov 16 '09 at 11:53
source share

By preserving the score, you violate the DRY principle , therefore, if you have no good reason, you should not.

+7
Nov 16 '09 at 11:53
source share

Another approach is to use a constant initialized over the values ​​() method.

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

Thus, you have an automatically updated constant and still avoid using the overhead "values ​​()".

+3
Feb 28 '16 at 0:37
source share



All Articles