Tuesday, September 21, 2010

Enums in java

In prior releases, the standard way to represent an enumerated type was the int Enum pattern:
// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL   = 3;
But these are not type safe, and clearly naming them is bit of a problem.
See here more for details. So in Java 5, they introduced Enums.

Defining Enums
Eg.
enum Season { WINTER, SPRING, SUMMER, FALL } 
public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }

public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }  
public enum Shape { RECTANGLE, CIRCLE, LINE } 
  
Note on Semicolon ( ; )
Enum embedded inside a class. Outside the enclosing class, elements are referenced as Outter.Color.RED, Outter.Color.BLUE, etc.
public class Outter {
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE
}
}

Declaring enum variables and using enum values

The enum class name can be use like any other class type in declarations. Usually enum values must be prefixed with the enum type name.

Shape drawing = Shape.RECTANGLE;   // Only a Shape value can be assigned.

Looping over all enum values with foreach loop

The static values() method of an enum type returns an array of the enum values. The foreach loop is a good way to go over all of them.

for ( Color c :Color.values() ) {
         System.out.print( c + " " );
}


Getting an integer equivalent of an enum value

Each enum value in an enum class has an associated default value, starting with zero for the first value and incrementing by one for each additional value. This may be accessed with the ordinal() method.
System.out.println(drawing.ordinal());     // Prints 0 for RECTANGLE.
 

Input (Convert string to enum)

The valueOf() method can be used to convert a string value to an enum value. Here is an example of reading in a Shape value from a Scanner object in.
drawing = Shape.valueOf(in.next());
 
or
drawing = Shape.valueOf("RECTANGLE");
 
The static methods valueOf() and values() are created at compile time and do not appear in source code. 
They do appear in Javadoc, though; 
 
Read more in Effective java for better practises.
 

No comments:

Post a Comment

Chitika