在 Java 中有一种方法可以定义 char 类型的枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14202959/
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
In Java is there a way to define enum of type char
提问by C graphics
I was wondering if we can have enaum values of type char? I would like to do something like this:
我想知道我们是否可以拥有 char 类型的 enaum 值?我想做这样的事情:
public enum Enum {char X, char Y};
...
Enum a=Enum.X
if (a=='X')
{// do something}
without calling any extra function to convert enum to char( as I want it to be char already). Is there a way to do so?
无需调用任何额外的函数将枚举转换为字符(因为我希望它已经是字符)。有没有办法这样做?
- In fact this way I am trying to define a restricted variable of type char which only accepts one of two char values 'X' or 'Y'. So that if we give anything else such as 'z', the compiler complains.
- 事实上,我试图通过这种方式定义一个 char 类型的受限变量,它只接受两个 char 值“X”或“Y”之一。因此,如果我们给出其他任何内容,例如“z”,编译器就会抱怨。
回答by yshavit
No.
不。
But the conversion method isn't very hard, at all.
但是转换方法一点也不难。
public enum SomeChar {
X('X'), Y('Y');
public char asChar() {
return asChar;
}
private final char asChar;
SomeChar(char asChar) {
this.asChar = asChar;
}
}
And then:
接着:
if (a.asChar() == 'X') { ... }
If you don't like having the asChar field/constructor, you can even implement the getter as return name().charAt(0)
.
如果您不喜欢 asChar 字段/构造函数,您甚至可以将 getter 实现为return name().charAt(0)
。
If you're using lombok, this becomes even easier:
如果您使用lombok,这将变得更加容易:
@RequiredArgsConstructor
@Getter
public enum SomeChar {
X('X'), Y('Y');
private final char asChar;
}
if (a.getAsChar() == 'X') { ...
Btw, an enum named Enum
would be confusing, since most people will see Enum
in the source and assume it's java.lang.Enum
. In general, shadowing a commonly used/imported class name is dangerous, and classes don't get more commonly imported than java.lang.*
(which is always imported).
顺便说一句,命名的枚举Enum
会令人困惑,因为大多数人会Enum
在源代码中看到并假设它是java.lang.Enum
. 一般来说,隐藏常用/导入的类名是危险的,并且类不会比java.lang.*
(总是导入的)更常用。