我有一个Java的枚举:
public enum Months
{
JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC
}
Run Code Online (Sandbox Code Playgroud)
我想通过索引访问枚举值,例如
Months(1) = JAN;
Months(2) = FEB;
...
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
Har*_*Joy 208
试试这个
Months.values()[index]
Run Code Online (Sandbox Code Playgroud)
Tre*_*ick 20
这有三种方法.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我只是尝试了相同的方法并提出了以下解决方案:
public enum Countries {
TEXAS,
FLORIDA,
OKLAHOMA,
KENTUCKY;
private static Countries[] list = Countries.values();
public static Countries getCountry(int i) {
return list[i];
}
public static int listGetLastIndex() {
return list.length - 1;
}
}
Run Code Online (Sandbox Code Playgroud)
该类将自己的值保存在数组中,我使用该数组获取索引位置处的枚举。如上所述,数组从 0 开始计数,如果您希望索引从 '1' 开始,只需将这两种方法更改为:
public static String getCountry(int i) {
return list[(i - 1)];
}
public static int listGetLastIndex() {
return list.length;
}
Run Code Online (Sandbox Code Playgroud)
在我的 Main 中,我获得了所需的国家/地区对象
public static void main(String[] args) {
int i = Countries.listGetLastIndex();
Countries currCountry = Countries.getCountry(i);
}
Run Code Online (Sandbox Code Playgroud)
将 currCountry 设置为最后一个国家,在本例中为 Country.KENTUCKY。
请记住,如果您使用硬编码索引来获取对象,则此代码受 ArrayOutOfBoundsExceptions 的影响很大。
| 归档时间: |
|
| 查看次数: |
124020 次 |
| 最近记录: |