javaenumscastingenumeration

How to cast a value from one enum to another in Java?


How can I cast a value from Enum1 to Enum 2 in Java? Here is an example of what I'm trying to do :

public enum Enum1 {
  ONE,
  TWO,
  THREE;
}

public enum Enum2 {
  FOUR,
  FIVE,
  SIX;
}

So I want to do something like this:

Enum2 en2 = (Enum2)ONE;

Is it possible and how can I do that?

Thanks in advance!


Solution

  • You cannot cast from one enum to another, however each enum has guaranteed order, and you can easily translate one enum to another (preserving order). For example:

    enum E1 {
        ONE, TWO, THREE,
    }
    
    enum E2 {
        ALPHA, BETA, GAMMA,
    }
    

    we can translate E1.TWO to/from E2.BETA by:

    static E2 E1toE2(E1 value) {
        return E2.values()[value.ordinal()];
    }
    
    static E1 E2toE1(E2 value) {
        return E1.values()[value.ordinal()];
    }