Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

enums

I was wondering if we can have enaum values of type char? 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). 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.
like image 408
C graphics Avatar asked Jan 07 '13 19:01

C graphics


People also ask

Can enum have char value?

The enum does have an int as a backing type (as it's the default). The char values that are used in the definition are implicitly converted to int values.

Can enum be characters?

Using the Code First of all, YES, we can assign an Enum to something else, a char !

How enum define datatype in Java?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

How do you define enum data type?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.


1 Answers

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).

If you're using lombok, this becomes even easier:

@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).

like image 119
yshavit Avatar answered Oct 04 '22 05:10

yshavit