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!
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.
You cannot have an enum extend another enum , and you cannot "add" values to an existing enum through inheritance.
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).
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()];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With