Ask Your Question
1

How can Enum values be transformed into integers in both "Enum" and "Enum Class"?

asked 2022-08-31 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-07-27 16:00:00 +0000

david gravatar image

In both "Enum" and "Enum Class", Enum values can be transformed into integers by using the default method "ordinal()". The "ordinal()" method returns the zero-based position of the enum constant in the list of constants. For example, consider the following enum class:

enum Color {
  RED, GREEN, BLUE;
}

To get the integer value of an enum constant, you can call its ordinal() method like this:

Color c = Color.RED;
int value = c.ordinal(); // value will be 0

Note that ordinal values start at 0 for the first constant in the list and increment by 1 for each subsequent constant. So, in this example, RED has an ordinal value of 0, GREEN has an ordinal value of 1, and BLUE has an ordinal value of 2.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-31 11:00:00 +0000

Seen: 1 times

Last updated: Jul 27 '21