在 Java 中嵌套枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6424390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nesting enums in Java
提问by PaulJWilliams
I want to nest some enums. The object i'm representing are Flags, with a type, and a value. There are a discrete number of types, and each type has a distinct set of possible values.
我想嵌套一些枚举。我代表的对象是标志,具有类型和值。有离散数量的类型,每种类型都有一组不同的可能值。
So if Type A can have values 1, 2 or 3, and Type B can have values 4,5,6, I'd like to be able to do things like:
因此,如果类型 A 可以具有值 1、2 或 3,类型 B 可以具有值 4、5、6,我希望能够执行以下操作:
Flag f = Flag.A.1;
f.getType() - returns "A"
f.getValue() - returns "1"
Flag f2 = Flag.A.4; -- Syntax error.
I'm driving myself crazy trying to nest enums within enums - is what i'm trying possible - do I need to ditch enums altogether and handcraft a static class with static members?
我试图将枚举嵌套在枚举中让自己发疯-这是我正在尝试的可能-我是否需要完全放弃枚举并使用静态成员手工制作一个静态类?
My best effort so far is:
到目前为止,我最大的努力是:
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:
但如果我这样做:
Flag f = Flag.A.ONE;
The types are incompatible.
类型不兼容。
回答by Peter Lawrey
You cannot have a number as an enum. It has to 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 a 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;
回答by Michael Borgwardt
Nesting enums is not possible. But enums can implement interfaces. Why not have A
and B
as two different enums that both implement a TypedEnum
interface with getType()
and getValue()
methods?
嵌套枚举是不可能的。但是枚举可以实现接口。为什么不将A
andB
作为两个不同的枚举来实现TypedEnum
接口getType()
和getValue()
方法呢?
回答by Rostislav Matl
As I understand enums, they are kind of singletons. It means enum X {A,B} has two singleton instances A,B. If you had nested enum A { P, Q }, how you can say if X.A is X.A.P or X.A.Q ? I wish I was able to say it more simply.
据我了解枚举,它们是一种单身人士。这意味着 enum X {A,B} 有两个单例实例 A,B。如果你有嵌套的枚举 A { P, Q },你怎么能说 XA 是 XAP 还是 XAQ ?我希望我能说得更简单。
Use static class.
使用静态类。