enum : Java Glossary
home E words local find no local find frame, full screen Google search web for topic jump to footer translate with Babelfish 2008-03-24 by Roedy Green ©1996-2008 Canadian Mind Products
Go to : punctuation 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z (all)
enum
Java 1.5+ has built-in support for enumerated types. Prior to that you had to kludge them in some way with static final ints (which were not typesafe) or with Objects which would not work in switch statements.
Enum Basics Under The Hood (2)
Sample Code Under The Hood (3)
Common Methods The Good
To & From Ordinal The Bad
Built-in Methods Alias Values
Individual Methods Data Bases
Getting Fancy Learning More
Nested enums Links
Under The Hood (1)

Enum Basics

Don’t confuse enum with the Enumeration interface, an almost obsolete way of iterating over Collections, replaced by Iterator.

Java 1.5 enums are references to a fixed set of Objects than represent the various possible choices. enums handle single choices, not combinations of choices. For combinations, you need EnumSet. For HashMap-style lookups when the key in an enum, you need EnumMap.

Enum and the enum constants are just classes. Since enum constants are constants, normally they should be all capitalised. However, since the constant name is the same as what is displayed externally, some people relax that rule and name constants with upper or lower case names as appropriate for the application. Note that you can’t call your enums default or null since these are reserved words. Try usual or none.

enums you want widely known should be put in the their own source file and given the attribute public. You then import the enum, as you would any other class.

Needless to say, enums are type safe. If you try to store an enum constant for a dog Breed into a Locomotive type enum variable, the compiler will refuse.

Sample Code using enum

Enum Constants Can Have Common Methods

In this simple example, the enum constants each have an instance field colours and an instance method getColours.

To & From Ordinal

// T O   A N D   F R O M   O R D I N A L

// To Ordinal
Breed dog = Breed.LABRADOR;
int ordinal = dog.ordinal();  // LABRADOR = 2

// From Ordinal
int ordinal = 2;
Breed dog = Breed.values()[ ordinal ];   // LABRADOR = 2

Built-in Methods

All enums and enum constants have some built-in methods:

Enum Constants Can Have Individual Methods

There are three basic ways to write an method for use by an enum constant:
  1. Single common method for all enum constants. It works with different constants passed in the constructor. The method is part of your enum class as a whole.
  2. An abstract or default method in the enum class as a whole, and each enum constant overrides it.
  3. enum constants have peculiar methods all their own. If two enum constants implement the same method, they are only incidentally related.

Getting Fancy

enum constants can even each have their own little anonymous inner class complete with constructors, methods and variables. See the Under the Hood (3) example below.

I use enums for writing the finite state automata that colourise all the listings on my website. Each state is represented by one enum constant. Each enum constant has custom logic to figure out the next state. The enum as a whole has both static and instance methods, and the enum constants override some of the instance methods. That allows a default implementation for a method that all enum constants must implement. I can invoke the method by the common base name, just as with classes and subclasses.

It is easiest to use public or top-level enums. Begin your experiments with public enums in their own *.java file to avoid frustration. I have managed to get nested static enums and nested inner enums to work as well, at least for the simple case where the enum constants have no constructors or individual classes. Even when you don’t specify static, nested enum classes are considered static. They don’t require an associated outer class object. There are no such thing as anonymous enums, and if there were, they would not be very useful since their enum constants would be anonymous too.

Unlike most of Java, you need to understand how enums work under the hood. When you understand the inner class structure, everything makes sense. Without that understanding enums will drive you insane with bizarre behaviour and restrictions.

Nested enums

An enum is a species of class, so it can be a public class, a top level default class or a nested static class. Inner class enums are considered static even if you don’t use the static keyword. An enum follows the same scope and visibility rules as any other class.

I recommend using only public enums and putting them each one in its own *.java file. However, you can also create toplevel enums, and static enums like this:

All enums support both static and instance fields and methods of the enum as a whole. However, enum constants are fields that point to unique objects of the enum class with optional anonymous inner classes. They can thus include instance fields and methods, but not static, simply because for some idiotic reason all inner classes can’t support static fields and methods. Some believe the reason statics are not implemented was not laziness but rather a desire prevent programmers from using inner classes for purposes other than serving the outer class. One speculated the problem comes because there are actually two flavours of anonymous classes, those declared in a static and an instance context. Another explanation is that you run into chicken and egg initialisation problems if you allow static members.

Under The Hood (1)

Here is a simple program using enums and a switch. I have provided a commented decompilation so that you can see how enum pulls off its magic.
I wondered wonder why Sun didn’t just use the enum ordinals directly as case numbers. The tableswitch JVM instruction does an indexed lookup, which would be one level of indirection less than Sun’s enum scheme. Perhaps Sun was worried the compiler would sometimes generate a slower lookupswitch if the table were not dense or if it were large. With their preconditioning, they guarantee the table is both small and dense, which guarantees that the faster tableswitch instruction will be used. Sun could refine its technique by collapsing the lookupswitch table further by using the same case number for multiple case labels on the same code. Others have pointed out Sun’s indirect scheme provides additional binary compatibility. If class A has a switch statement involving enum B, and B acquires a new enum constant, even one in the middle of the enumeration order, and A is not recompiled, the switch will still work (treating the new enum constant as part of the default category.

Under The Hood (2)

Here is a simple program using enum where the enum constants all use the same implementation of the same method and same instance field. I have provided a commented decompilation so that you can see how enum pulls off its magic.

Under The Hood (3)

Here is a simple program using enum where the one enum constant implements a method that the other enum constants do not. I have provided a commented decompilation so that you can see how enum pulls off its magic.

The Good About Enums

The Bad About Enums

Alias Values

Here is a simplified version of a program that lets you create a valueOf that accepts aliases in addition to the enum constant name.

Data Bases

How do you deal with storing enums in databases? Here are ways I would not recommend: Here are ways I would recommend: In your enum, you have a valueOf variant that accepts the database 2-char abbreviation using a hash-map constructed at load time from values() list. The 2-char names are defined in the enum constant constructors. This allows you to rapidly interconvert between enum ⇔ 2-char ⇔ internationalised String.

Storing invariant two-char codes in your SQL database will protect you from the main catastrophic error — out by one on your enum constants without noticing.

If a database contains an invalid 2-char code, you will detect the problem the instant your code encounters it. The error won’t stealthily skulk under the murk the way using ordinals permits.

Don’t use default in your switches. Then the compiler will notify you if you did not insert code to handle the new enum case.

If you use Applets, your client code can convert 2-char enums to internationalised strings. If you don’t, then your Servlets can do it. This should be considerably faster than getting your SQL database to do it by table look up.

Learning More

Sun’s JDK Technote Guide on enums : available:
Sun’s Javadoc on the Enum, the class underpinning enums class : available:
Sun’s Javadoc on the EnumMap class : available:

To Come

inner class gotchas


CMP_homejump to top
CMP logo
feedback Please email your feedback for publication, errors, omissions, broken/redirected link reports
and suggestions to improve this page to Roedy Green : feedback email
made with CSS
HTML Checked!
ICRA ratings logo
mindprod.com IP:[65.110.21.43]
Your face IP:[38.103.63.18] Spread the Net
You are visitor number 99,011.
You can get a fresh copy of this page from: or possibly from your local J: drive (Java virtual drive/Mindprod website mirror)
http://mindprod.com/jgloss/enum.html J:\mindprod\jgloss\enum.html