Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Enum Value from index in Java?

Tags:

java

enums

I have an enum in Java:

public enum Months {     JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC } 

I want to access enum values by index, e.g.

Months(1) = JAN; Months(2) = FEB; ... 

How shall I do that?

like image 847
jk_ Avatar asked Jul 14 '11 11:07

jk_


People also ask

Can you index an enum?

Use the Object. values() method to get an array containing the enum's values. Use square brackets to access the array at the specific index and get the value.

How do you find the enum index?

int eValue = (int)enumValue; However, also be aware of each items default value (first item is 0, second is 1 and so on) and the fact that each item could have been assigned a new value, which may not necessarily be in any order particular order!

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

What is ordinal in enum Java?

ordinal() tells about the ordinal number(it is the position in its enum declaration, where the initial constant is assigned an ordinal of zero) for the particular enum.


2 Answers

Try this

Months.values()[index] 
like image 171
Harry Joy Avatar answered Oct 01 '22 20:10

Harry Joy


Here's three ways to do it.

public enum Months {     JAN(1), FEB(2), MAR(3), APR(4), MAY(5), JUN(6), JUL(7), AUG(8), SEP(9), OCT(10), NOV(11), DEC(12);       int monthOrdinal = 0;      Months(int ord) {         this.monthOrdinal = ord;     }      public static Months byOrdinal2ndWay(int ord) {         return Months.values()[ord-1]; // less safe     }      public static Months byOrdinal(int ord) {         for (Months m : Months.values()) {             if (m.monthOrdinal == ord) {                 return m;             }         }         return null;     }     public static Months[] MONTHS_INDEXED = new Months[] { null, JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };  }     import static junit.framework.Assert.assertEquals;  import org.junit.Test;  public class MonthsTest {  @Test public void test_indexed_access() {     assertEquals(Months.MONTHS_INDEXED[1], Months.JAN);     assertEquals(Months.MONTHS_INDEXED[2], Months.FEB);      assertEquals(Months.byOrdinal(1), Months.JAN);     assertEquals(Months.byOrdinal(2), Months.FEB);       assertEquals(Months.byOrdinal2ndWay(1), Months.JAN);     assertEquals(Months.byOrdinal2ndWay(2), Months.FEB); }  } 
like image 43
Trever Shick Avatar answered Oct 01 '22 20:10

Trever Shick