简体   繁体   English

在Java中有一种方法来定义char类型的枚举

[英]In Java is there a way to define enum of type char

I was wondering if we can have enaum values of type char? 我想知道我们是否可以拥有char类型的enaum值? I would like to do something like this: 我想做这样的事情:

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). 没有调用任何额外的函数将枚举转换为char (因为我希望它已经是char)。 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'. 实际上这种方式我试图定义一个char类型的限制变量,它只接受两个char值'X'或'Y'中的一个。 So that if we give anything else such as 'z', the compiler complains. 因此,如果我们提供其他任何内容,例如'z',编译器会抱怨。

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 . 顺便说一句,一个名为Enum会令人困惑,因为大多数人会在源代码中看到Enum并假设它是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). 通常,遮蔽常用/导入的类名是危险的,并且类的导入不会比java.lang.* (总是导入的)更常导入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM