I am an almost-graduating computer science student, and throughout my coding career, I’ve found very few instances where enumerations, except for canonical cases such as representing the faces of a standard deck of cards, are used.
Do you know of any clever ways that enums are used in everyday coding?
Why are enumerations so important and in what situations should one be able to identify that building an enumeration is the best approach?
These are the main arguments for
enum,EnumMap, andEnumSetby short examples.The case for
enumAs of Java 6,
java.util.Calendaris an example of a messy class that could’ve benefited a lot from usingenum(among other improvements).Currently
Calendardefines the following constants (among many others):These are all
int, even though they obviously represent different conceptual entities.The following are some serious consequences:
MONDAY = 0;,SUNDAY = 0;, then we haveMONDAY == SUNDAYint:setMonth(JANUARY), but we can alsosetMonth(THURSDAY)orsetMonth(42)set(int,int,int,int,int,int)(a real method!) does!By contrast, we could have something like this instead:
Now we never have to worry about
MONDAY == SUNDAY(it can never happen!), and sinceMonthandDayOfWeekare different types,setMonth(MONDAY)does not compile.Additionally, here are some before-and-after codes:
Here we’re making all sorts of assumptions, e.g.
JANUARY + 1 == FEBRUARY, etc. On the other hand, theenumcounterpart is both more concise, more readable, and makes less assumptions (and therefore less chance for bugs):The case for instance fields
In Java,
enumis aclassthat has many special properties, but aclassnonetheless, allowing you to define instance methods and fields if necessary.Consider the following example:
On the other hand, with
enumyou can write something like this:The case for instance methods
Consider the following example:
As shown in previous example,
enumin Java can have instance methods, but not only that but each constant can have its own specific@Overrideas well. This is shown in the following code:The case for
EnumMapHere’s a quote from Effective Java 2nd Edition:
Essentially where as before you may have something like this:
Now you can have:
The case for
EnumSetPower of two
intconstants are often used e.g. in C++ to denote bit sets. This relies on bitwise operations. An example may look something like this:With
enumandEnumSet, this can look something like this:References
See also
enuminstead ofintconstantsEnumSetinstead of bit fieldsEnumMapinstead of ordinal indexingRelated questions
ordinal(), however…EnumSet!