Nesting enumerations in Java
•
Java
I want to nest some enumerations The object I represent is flags, with type and value There are discrete types, each with a different set of possible values
So if type a can have a value of 1,2 or 3 and type B can have a value of 4,5,6, I want to be able to do the following:
Flag f = Flag.A.1; f.getType() - returns "A" f.getValue() - returns "1" Flag f2 = Flag.A.4; -- Syntax error.
I'm frantically trying to nest enums in enums - the possibility I'm trying - do I need to complete enumerations and manually create a static class with static members?
My best efforts so far are:
public class Flag {
enum A extends Flag {
ONE("ONE"),TWO("TWO"),THREE("THREE");
private A(String value) {
Flag.type = "A";
Flag.value = value;
}
}
private static String type;
private static String value;
}
But if I do this:
Flag f = Flag.A.ONE;
Incompatible types
Solution
You cannot have a number as an enumeration It must be an identifier
You can do this
interface Flag {
String getType();
int getValue();
enum A implements Flag{
one,two,three;
String getType() { return getClass().getSimpleName(); }
int getvalue() { return ordinal()+1; }
}
enum B implements Flag{
four,five,six;
String getType() { return getClass().getSimpleName(); }
int getvalue() { return ordinal()+4; }
}
}
Flag f = Flag.A.one;
However, the simpler option may be
enum Flag {
A1,A2,A3,B4,B5,B6;
public String getType() { return name().substring(0,1); }
public int getValue() { return name().charAt(1) - '0'; }
}
Flag f = Flag.A1;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
