Friday, December 2, 2011

Enumerating

Sometimes when you are programming, you come across situations where you need some constants but the constants all have something significant in common. Take for example a program which tracks a person's food intake. You might want to categorize each of the foods in the program's database.

You might create constants like this:

public static final int PROTEIN   = 0;
public static final int GRAINS    = 1;
public static final int VEGETABLE = 2;
public static final int FRUIT     = 3;
public static final int FATS      = 4;
public static final int DAIRY     = 5;
public static final int SUGARS    = 6;


Another way to accomplish the same goal is instead of having a bunch of non-related constants, create an enumerated list of constants like so:

public static enum FoodGroup {
   PROTEIN, GRAINS, VEGETABLE,
   FRUIT, FATS, DAIRY, SUGARS }


You can switch on an enumerated type just like with integers and characters and your code becomes very easily readable.

FoodGroup fg;
// code here sets fg among other things

switch ( fg )
{
   case PROTEIN:

// code to handle protein case here
}

Very easy to use and all of your related constants are handled in one tidy location.

A slightly more complex situation arises when you want to define the actual values of the constants. Your basic enumerated list begins at zero and assigns incremental integer values to each item in the enumerated list.

Suppose you want to assign the value -1 to NEGATIVE, 0 to ZERO, and +1 to POSITIVE? How can you make that happen in Java? Like this:

public static enum Sign
{
   NEGATIVE(-1), ZERO(0), POSITIVE(1);
   private int value;
   private Sign(int v)
   {   this.value = v;   }
};


The difference here is that you need a constructor and a private data member. Still works the same in code later...