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.
Jon Skeet Nov 16 '09 at 11:54 2009-11-16 11:54
source share