Enumeration Type with Numeric Constant

I get data from a legacy system where a specific single-byte field is a code that can contain a letter or number. I want to match it with an enumeration, but I'm not sure how to handle numeric values.

public enum UsageCode {
    A ("Antique"),
    F ("Flood Damaged"),
    N ("New");
//  0 ("Unknown")  How to allow for value of "0"?

    private final String description;

    UsageCode(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }
}
+5
source share
2 answers

Turn inside out:

public enum UsageCode {
    ANTIQUE ('A'),
    FLOOD_DAMAGED ('F'),
    NEW ('N');
    UNKNOWN ('0')

    private static final Map<Character, UsageCode> charToEnum
            = new HashMap<Character, UsageCode>();

    static { // Initialize map from legacy code to enum constant
        for (UsageCode code : values())
        charToEnum.put(code.getCode(), code);
    }

    // Returns UsageCode for legacy character code, or null if code is invalid
    public static UsageCode fromLegacyCode(char code) {
        return charToEnum.get(code);
    }

    private final char code;

    UsageCode(char code) {
        this.code = code;
    }

    public char getCode() {
        return code;
    }
}

To convert incoming character codes to enumeration values, I added an internal Map<Character, UsageCode>and static conversion method.

Example adapted from Effective Java 2nd Edition , paragraph 30.

+7
source

You can do this in a different way, having a significant constant and preserving the representation of the deprecated value:

public enum UsageCode {

   ANTIQUE("A"),
   FLOOD_DAMAGED("F"),
   NEW("N"),
   UNKNOWN("0");

   private String legacy;

   private UsageCode(String legacy) {
      this.legacy = legacy;
   }

   public static UsageCode toUsageCode(String legacyOutput) {
      for(UsageCode code : values()) {
         if (code.legacy.equals(legacyOutput)) {
            return code;
         }
      }
      return null;
   }
}
+5
source

All Articles