Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 923
Android-Droid Avatar asked Sep 02 '11 13:09

Android-Droid


People also ask

How do I convert one enum to another in Java?

A cast operation is not possible, but you can write a static member function for enum1 that casts enum2 to enum1: public static Enum1 fromEnum2(Enum2 enum2) { ... } By the way, you can assign an ID to every constant of both enums which simplifies the implementation.

Can enum inherit from another enum Java?

You cannot have an enum extend another enum , and you cannot "add" values to an existing enum through inheritance.

Can enum have another enum?

An enum can, just like a class , have attributes and methods. The only difference is that enum constants are public , static and final (unchangeable - cannot be overridden). An enum cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).


1 Answers

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()];
}
like image 58
Michał Šrajer Avatar answered Sep 19 '22 14:09

Michał Šrajer