November 2004
Intermediate to advanced
400 pages
10h 31m
English
You need an Enum, but you are not using the new Java 1.5 release.
If you are stuck with Java 1.4 or lower, you can use Commons Lang
Enum, ValuedEnum, and
EnumUtils to create an enum
“type,” which approximates the new
language feature. Example 1-10 extends Enum,
providing three flavors: Flavor.CHOCOLATE,
Flavor.VANILLA, and
Flavor.STRAWBERRY.
Example 1-10. Defining a Flavor enumeration by extending Enum
import java.util.*;
import org.apache.commons.lang.enum.Enum;
public final class Flavor extends Enum {
public static Flavor CHOCOLATE = new Flavor( "Chocolate" );
public static Flavor VANILLA = new Flavor( "Vanilla" );
public static Flavor STRAWBERRY = new Flavor( "Strawberry" );
private Flavor(String name, int value) { super( name, value ); }
public static Flavor getEnum(String flavor) {
return (Flavor) getEnum(Flavor.class, flavor);
}
public static Map getEnumMap( ) {
return getEnumMap(Flavor.class);
}
public static List getEnumList( ) {
return getEnumList(Flavor.class);
}
public static Iterator iterator( ) {
return iterator(Flavor.class);
}
}The key to an Enum is the private constructor;
this guarantees that there are only three instances of
Flavor in any virtual machine. This extension of
Enum provides a number of useful utilities to get
a List or Map of available
Flavor instances:
// Using Flavor to create an ice cream cone IceCreamCone cone = new IceCreamCone( ); cone.setScoops( 5 ); cone.setFlavor( Flavor.VANILLA ); cone.addTopping( "sprinkles" ...
Read now
Unlock full access