Home | FAQ | Contact me

Java 5 Enumerations


Singing the tune of working out the remaining kinks in my understanding of Java 5 goodies after employment that constrained me to writing only Java 1.4-compatible code (see Generics), let's see what we can do with enumerations.

Here are a few reasonable examples to copy and modify.




Eclipse tip: Adding plug-ins to Eclipse

It's easy to upgrade Eclipse to do lots of handy little things and important big things.

For example, AnyEdit will remove dead, white space from your source code and perform other menial tasks such converting characters to HTML graphemes, variables with underscores to camel-back case or vice-versa.

Pull down the Help menu, choose Install New Software..., then type http://andrei.gmxhome.de/eclipse/ into Work with:. Patiently await options to show up in the window in the middle. Check the triangle next to Eclipse 3.3 - 3.5 plugins and check the AnyEdit box.

If you get a failure containing things like:

No repository found...
session context was:(profile=epp.package.jee, phase=org.eclipse.equinox.internal.provisional.p2.engine.phases.Collect, operand=, action=).

...then close Eclipse and relaunch thus: eclipse -clean.

A very simple enumeration:

public enum MuscleCarsOfThe1960s
{
    Dodge_Charger,
    Plymouth_Barracuda,
    Plymouth_RoadRunner,
    Plymouth_SuperBird,
    Chevrolet_Chevelle_Malibu_SS,
    Chevrolet_Impala_SS,
    Oldsmobile_442,
    Pontiac_GTO,
    Ford_Thunderbolt,
    Ford_Mustang_Mach_I
}

How to enumerate the values of a Java enumeration:

for( MuscleCarsOfThe1960s muscleCar : MuscleCarsOfThe1960s.values() )
  System.out.println( muscleCar );

—output looks like this:

    Dodge_Charger
    Plymouth_Barracuda
    Plymouth_RoadRunner
    Plymouth_SuperBird
    Chevrolet_Chevelle_Malibu_SS
    Chevrolet_Impala_SS
    Oldsmobile_442
    Pontiac_GTO
    Ford_Thunderbolt
    Ford_Mustang_Mach_I

Use an enumeration thus:

MuscleCarsOfThe1960s car = MuscleCarsOfThe1960s.Dodge_Charger; . . . if( car == MuscleCarsOfThe1960s.Oldsmobile_442 ) ...

A more complex enumeration that saves state for a purpose.

public enum OperatingSystem
{
    LINUX,
    WINDOWS,
    UNKNOWN;

    private static OperatingSystem currentSystem = UNKNOWN;

    public static OperatingSystem system()
    {
        if( currentSystem == UNKNOWN )
        {
            String osname = System.getProperty( "os.name" );

            if( osname.startsWith( "Linux" ) )
                currentSystem = LINUX;
            else if( osname.startsWith( "Windows" ) )
                currentSystem = WINDOWS;
            else
                currentSystem = UNKNOWN;
        }

        return currentSystem;
    }
}

The above enumeration is practical for uses such as:

if( OperatingSystem.system() == OperatingSystem.LINUX ) ...

External use of enumerations

As implied by the sample usage of the last example, you must use the type (here, OperatingSystem) when referring to any of the enumeration values, but, because of the type of the discriminator, this is not necessary in a switch statement. Assume the following is coded in a class that consumes enum OperatingSystem:

    .
    .
    .
    OperatingSystem system = OperatingSystem.system();

    if( system == LINUX )                   // (syntax error!)
        ...

    if( system == OperatingSystem.LINUX )   // (the correct way)
        ...

    switch( system )                        // (good because compiler understands 'system')
    {
       case LINUX :
           System.out.println( "This is Linux!" );
           break;
       case WINDOWS :
           System.out.println( "This is Windows!" );
           break;
       default :
       case UNKNOWN :
           System.out.println( "The operating system is unknown!" );
           break;
    }
    .
    .
    .

Initializing enumeration values

Of course, you can always do the following and take advantage of the fact that the values can be integers.

    public enum Color
    {
        black (0),
        white (1),
        red   (2),
        yellow(3),
        pink  (4),
        green (5),
        orange(6),
        purple(7),
        blue  (8);

        private int color;

        private Color( int c ) { this.color = c; }
        public int getColor()  { return this.color; }

        @Override
        public final String toString()
        {
            String	string = null;

            switch( this )
            {
                case black :  string = "black";  break;
                case white :  string = "white";  break;
                case red :    string = "red";    break;
                case yellow : string = "yellow"; break;
                case pink :   string = "pink";   break;
                case green :  string = "green";  break;
                case orange : string = "orange"; break;
                case purple : string = "purple"; break;
                case blue :   string = "blue";   break;
           }

           return string;
        }
    }

For a similar example, using Strings instead of integers, see here.

This next example illustrates some of the oblique power behind initialization of Java 5's enum type. With an object of JdbcEntity, entity, many expressions are possible that abbreviate and clarify JDBC operation code.

entity.getTableName(); entity.getReferenceColumn(); switch( entity ) { case User : . . . }

Etc. Here's the enum definition. Note that to do this (rather bizarre) sort of enumeration, you must have a (private) constructor that provides for its construction. Hence the constructor below isn't callable outside.

public enum JdbcEntity
{
    // authorization entity is a user, group, etc...
    User    ( "t_attr_user",  "user_id" ),
    Group   ( "t_attr_group", "group_id" ),
    Role    ( "t_attr_role",  "role_id" ),
    Resource( "t_attr_rsrc",  "rsrc_id" );

    private String tableName;  // table in which attributes will be stored
    private String refColumn;  // reference column in the table

    /**
     * Private constructor.
     */
    private JdbcEntity( String table, String column )
    {
        this.tableName = table;
        this.refColumn = column;
    }

    public String getTableName()       { return this.tableName; }
    public String getReferenceColumn() { return this.refColumn; }
}

And, again, another example...

public enum Genre
{
	Action    ( "Action"          ),
	Adventure ( "Adventure"       ),
	Allegory  ( "Allegory"        ),
	Cartoon   ( "Cartoon"         ),
	Chick     ( "Chick flick"     ),
	Comedy    ( "Comedy"          ),
	Drama     ( "Drama"           ),
	Fantasy   ( "Fantasy"         ),
	History   ( "History"         ),
	Military  ( "Military"        ),
	Music     ( "Music"           ),
	Musical   ( "Musical"         ),
	Mystery   ( "Mystery "        ),
	Politics  ( "Politics"        ),
	Religious ( "Religious"       ),
	Science   ( "Science fiction" ),
	Suspense  ( "Suspense"        ),
	Thriller  ( "Thriller"        );

	private String	genre = null;

	private                Genre( String genre ) { this.genre = genre; }
	public final void   setGenre( String genre ) { this.genre = genre; }
	public final String getGenre()               { return this.genre; }
}