thunderousNinja
thunderousNinja

Reputation: 3520

Quick Enum Question

Hey guys, I have a quick question. If given a string Value how can i get the corresponding int value in my enum class?

Ex:

Given a string "Ordinary" I want the value 0 returned. Here is what I have:

public enum MembershipTypes 
{
    ORDINARY(0,"Ordinary"),
    WORKING(1,"Working"),
    CORE(2,"Core"),
    COORDINATOR(3,"Coordinator");

    private int intVal;
    private String strVal;

    /**
     * 
     * @param intValIn
     * @param strValIn
     */
    MembershipTypes(int intValIn, String strValIn)
    {
        intVal = intValIn;
        strVal = strValIn;
    }

    /**
     * 
     * Gets the integer value
     * @return intVal
     */
    public int getIntVal() 
    {
        return intVal;
    }

    /**
     * 
     * Gets the string value
     * @return strVal
     */
    public String getStrVal() 
    {
        return strVal;
    }
}

Upvotes: 1

Views: 236

Answers (4)

Eng.Fouad
Eng.Fouad

Reputation: 117589

I think you can use ordinal().

Upvotes: 0

Puce
Puce

Reputation: 38132

Use:

private static final Map<String, MEMBERSHIP_TYPES> MEMBERSHIP_TYPES = new HashMap<String, MembershipTypes>;
static {
  for (MembershipTypes membershipType : values()){
     MEMBERSHIP_TYPES.put(membershipType.strVal, membershipType);
  }
}

public static int getIntVal(String strVal){
  if (! MEMBERSHIP_TYPES.containsKey(strVal){
     throw new IllegalArgumentException("Unknown value: " + strVal);
  }
  return MEMBERSHIP_TYPES.get(strVal).getIntVal();
}

Consider:

  • renaming MembershipTypes to MembershipType
  • renaming intVal and strVal to more meaningful property names if possible

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

Your enum automatically gets a method valueOf(String) that returns the right enum when given an enum name. You can override that to also check for your strVal. Alternatively, you could write a utility function that returns the int value directly.

Upvotes: 0

benjismith
benjismith

Reputation: 16735

Here's the simplest way to do it. Add this static method to your enum:

public static int getIntValForString(String strVal) {
   for (MembershipTypes e : MembershipTypes.values()) {
      if (e.getStrVal().equals(strVal)) {
         return e.getIntVal();
      }
   }
   throw new IllegalArgumentException("No such enum for string val:" + strVal);
}

Upvotes: 1

Related Questions