Thursday, August 14, 2008

Java 5 Enums rule!

After reading a section from my new Effective Java 2nd edition book I realized that I was using the new Enums incorrectly. I was using the ordinal when I should have been using the EnumMap type to map/reference variables assigned to each enum. An example would explain better.

public enum StatusType {
READY(true),
HOLDING(false),
HOLD_NOW(false);

public final boolean warnClient;

StatusType(boolean warn)
{
warnClient = warn;
}
};

Previously I was doing something like this:

ArrayList warnings = new ArrayList(StatusType.values().length);
for(StatusType type: StatusType.values())
{
warnings.add(type.warnClient);
}

and to access that I'd do:

for(StatusType type: StatusType.values())
{
boolean warn = warnings.get(type.ordinal());
something.enable(warn);
}

This is not great for a number of reasons, and the better implementation is to use an equally efficient EnumMap like so:

EnumMap map = new EnumMap(StatusType.class);

for( StatusType type: StatusType.values())
{
map.set(type, type.warn);
}

and then to access

for( StatusType type: StatusType.values())
{
boolean warn = map.get(type);
something.setEnabled(warn);
}

Using an EnumMap is much safer than using an ArrayList as it is fairly easy to overrun the ArrayList unless you know to use the .ordinal() so it's much less safe than using enum values as in the EnumMap method. Also, the ordinal() call isn't supposed to be used by developers using Java.

0 comments:

Buy Prints

Search darrickcoleman.com

Blog Archive

  © Blogger template 'Photoblog II' by Ourblogtemplates.com 2008

Back to TOP