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?
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.
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!
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.)
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.
Try this
Months.values()[index]
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With