Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get enum's numeric value?

Tags:

java

enums

Suppose you have

public enum Week {     SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } 

How can one get int representing that Sunday is 0, Wednesday is 3 etc?

like image 322
James Raitsev Avatar asked Jul 18 '12 20:07

James Raitsev


People also ask

What is enum number?

Numeric Enum Numeric enums are number-based enums i.e. they store string values as numbers. Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.

How do I assign an enum to an integer?

To convert a string to ENUM or int to ENUM constant we need to use Enum. Parse function. Here is a youtube video https://www.youtube.com/watch?v=4nhx4VwdRDk which actually demonstrate's with string and the same applies for int.

What is enumeration in C# with example?

In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer values. It makes constant values more readable, for example, WeekDays.


2 Answers

Week week = Week.SUNDAY;  int i = week.ordinal(); 

Be careful though, that this value will change if you alter the order of enum constants in the declaration. One way of getting around this is to self-assign an int value to all your enum constants like this:

public enum Week  {      SUNDAY(0),      MONDAY(1)       private static final Map<Integer,Week> lookup            = new HashMap<Integer,Week>();       static {           for(Week w : EnumSet.allOf(Week.class))                lookup.put(w.getCode(), w);      }       private int code;       private Week(int code) {           this.code = code;      }       public int getCode() { return code; }       public static Week get(int code) {            return lookup.get(code);       } } 
like image 165
Istvan Devai Avatar answered Sep 29 '22 01:09

Istvan Devai


You can call:

MONDAY.ordinal() 

but personally I would add an attribute to the enum to store the value, initialize it in the enum constructor and add a function to get the value. This is better because the value of MONDAY.ordinal can change if the enum constants are moved around.

like image 44
vainolo Avatar answered Sep 28 '22 23:09

vainolo