0

Given the following definitions:

public enum SampleEnum1 { Uno, Dos, Tres }
public enum SampleEnum2 { One, Two, Three, Four }

I need two methods doing this:

  • Given the integer 2, return Dos if applied to SampleEnum1, Two if applied to SampleEnum2
  • Given the value One, return 1

In fact I need to translate an enumeration litteral into its sequence number in the enumeration definition, and vicae versa.

I don't mind using generics, reflexion, or whatever, as long as the same 2 methods work for any enumeration.

Do you have the solution?

Joel
  • 3,427
  • 5
  • 38
  • 60
  • 1
    This has been answered over here: http://stackoverflow.com/questions/5021246/conveniently-map-between-enum-and-int-string – aioobe Jun 03 '11 at 10:50

3 Answers3

1

If you can be sure to keep your enums in order in the source file, you can do like this to get the enum by number:

public static SampleEnum1 getSpanishEnum(int index) {
    return SampleEnum1.values()[index - 1];
}

public static SampleEnum2 getEnglishEnum(int index) {
    return SampleEnum2.values()[index - 1];
}

And to go the other way, you can do a loop

public static <E extends Enum> getEnumIndex(E value, E[] values) {
    for(int i = 0; i < values.length; i++) {
        if(value == values[i]) {
            return i + 1;
        }
    }
    throw new NoSuchElementException();
}

calling it like this:

getEnumIndex(SampleEnum1.Dos, SampleEnum1.values());
stevevls
  • 10,675
  • 1
  • 45
  • 50
1

Another approach is to use a helper method like

public static <E etxends Enum<E>> E lookup(Class<E> eClass, int number) {
     return eClass.getEnumConstants()[number-1];
}

SampleEnum1 se1 = lookup(SampleEnum1.class, 2);

BTW: You could start with Zero which would simplify your code as well.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Thank you, what i was looking for. And `ordinal()` is the opposite function I needed. – Joel Jun 03 '11 at 11:09
1

The forward direction can be done using the Class.getEnumConstants() method:

  public static <E extends Enum<E>> E getValue(Class<E> eClass, int index) { 
      return eClass.getEnumConstants()[index - 1];
  }

Called as follows:

  SampleEnum2 two = getValue(SampleEnum2.class, 2);

(Unfortunately, we can't write a generic method that uses the values() method that every enum has. It is static so we can't access it by polymorphic dispatching. To access it reflectively we'd need to know the actual class of E ... and that requires a Class<E> object. And if you have to pass that, you may as well call its getEnumConstants method.)


The reverse direction is simpler:

  public static <E extends Enum<E>> int getIndex(E e) { 
      return e.ordinal() + 1; 
  }

Of course, it is much neater if you follow the normal IT convention that the indexes of a collection start from zero.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216