Advanced enum’s in Java

By | February 26, 2011

Ever since Java 1.4 the usage of the enum type is supported. For those who don’t know an enum is a more elegant way to store constant options. Below is a simple example of how it enhances your code:

public static final int ANIMAL_DOG    = 1;
public static final int ANIMAL_FISH   = 2;
public static final int ANIMAL_CAT    = 3;

Into something a bit more object oriented:

public enum Animal {

But when you have the need to serialize the enum values then you may have to use a bit complicator code. It is supported just not out of the box. So lets say I want to predefine the ordinal number and add a name for each animal in my enum. Then I would have to add something similar to this:

public enum Animal {
  Dog(10, 'Swoop doggie'),
  Fish(20, 'Blub'),
  Cat(30, 'Garfunkel');

  int iOrdinal;
  String iName;

  private Animal(int aOrdinal, String aName) {
    iOrdinal = aOrdinal;
    iName = aName;

Now each one of the enums values consists out of a name and a custom ordinal which can be used to save the value in a database or represent it in a form. Off course you would have to add methods to obtain the name and ordinal like:

public String getName()    { return iName; }
public int    getOrdinal() { return iOrdinal; }

That introduces a second problem, if you represent the enum Animal by its ordinal on for example a webpage you will need to be able to regenerate the correct enum value by its ordinal representation. To do this you could add a method to lookup the correct Animal for any ordinal like:

public static Animal getAnimal(int aOrdinal) {
 for(Animal lAnimal : values()) {
   if (lAnimal.getOrdinal() == aOrdinal) {
     return lAnimal;
 return Animal.Dog; // default value required

Leave a Reply