如何从Java中的索引获得枚举值?
我在Java中有一个枚举:
public enum Months { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC }
我想通过索引访问枚举值,例如
Months(1) = JAN; Months(2) = FEB; ...
我该怎么做?
尝试这个
Months.values()[index]
这里有三种方法来做到这一点。
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); } }
尝试使用EnumMap或EnumSet ?
查看关于枚举的java教程(行星示例)
http://download.oracle.com/javase/tutorial/java/javaOO/enum.html