15 April 2012

Java enum demo

import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

public enum EnumDemo {
  // For this enum each value has an identification code
  // other than the internal ordinal value
  DEMANDED(10),
  SPECIFIED(20),
  EVALUATED(30),
  DUPLICATE(33),
  ESTIMATED(35),
  WORKAROUND (36),
  ACCEPTED(37),
  PLANNED(40),
  BUSY(50),
  IMPLEMENTED(60),
  REJECTED(100);

  private int code;

  /**
   * @param code  constructor takes code to  be associated with enum
   */
  EnumDemo(int code) {
    this.code = code;
  }

  /**
   * Helper map for reverse lookup in getByCode method
   */
  private static Map<Integer,EnumDemo> enumByCode;
  static{
    enumByCode = new HashMap<Integer, EnumDemo>();
    for (EnumDemo val: EnumDemo.values()) {
      enumByCode.put(val.getCode(),val);
    }
  }

  public int getCode() {
    return code;
  }

  /**
   * reverse lookup
   * @param code the code of the enum
   * @return the enum or null if the code does not exist
   */
  public static EnumDemo getByCode(int code){
    return enumByCode.get(code);
  }

  /**
   * test if a code exists
   * @param code
   * @return  true if the code exists
   */
  public static boolean isCodeValid(int code){
    return enumByCode.containsKey(code);
  }

  /**
   * enumToString: EnumDemo.DEMANDED to "DEMANDED"
   * @return enum value name as a String
   */
  public String getName(){
    return toString();
  }

  /**
   * StringToEnum: "  demanded" to EnumDemo.DEMANDED
   * @param name case insensitive and leading and trailing spaces are ignored
   * @return  the enum constant
   */
  public static EnumDemo getByName(String name){
    return EnumDemo.valueOf(name.trim().toUpperCase());
  }
 
  /**
   * convert between enum and internal ordinal number
   * not recommended to expose this, just here for demo purposes
   * @return internal ordinal number of the constant
   */
  public int getOrdinal(){
    return getOrdinal();
  }
 
  /**
   * convert from ordinal number to enum. Not recommended.
   * @param ordinal
   * @return  the enum
   */
  public static EnumDemo getByOrdinal(int ordinal){
    return EnumDemo.values()[ordinal];
  } 
 
  // some tests and subsets
  // alternate methods can be written using the codes
    
  /**
   *
   * @return  is this enum in a range?
   */
  public boolean isOK(){
    return ACCEPTED.compareTo(this) <= 0 && IMPLEMENTED.compareTo(this)  >= 0;
  }

  /**
   * @return  an enum subrange
   */
  public static EnumSet<EnumDemo> getOK(){
    return EnumSet.range(ACCEPTED,IMPLEMENTED);
  }

  /**
   * @return  is this enum in a subset?
   */
  public boolean isNOK(){
    return this == DUPLICATE
      || this == WORKAROUND
      || this == REJECTED;
  }

  /**
   *
   * @return  get an enum subset
   */
  public static EnumSet<EnumDemo> getNOK(){
    return EnumSet.of(DUPLICATE,WORKAROUND,REJECTED);
  }
}