不能混淆,在一個開關。您可以將Test
枚舉傳遞給switch語句,也可以在case語句中使用常量標識。
我建議有一個映射cityId <-> Test instance
和轉換之前調用交換機。
喜歡的東西
Map<Integer, Test>` mapping = ...;
mapping.put(1234, Test.MOSCOW); //note the use of autoboxing
...
mapping.get(cityId); //note the use of autoboxing
編輯:請注意,你可以把這個映射到枚舉,一個cityId字段添加到枚舉和自動填寫由values()
返回的數組的映射,就像克里斯的建議, 。
public enum Test {
MOSCOW(1001),
NEWYORK(1002),
SOCHI(1234);
private final int cityId;
private Test(int cityId) {
this.cityId = cityId;
}
...
private static Map<Integer, Test> mapping = new HashMap<Integer, Test>();
static { //executed when the class is loaded
for(Test t : values()) {
mapping.put(t.getCityId(), t);
}
}
public static toTest(int cityId) {
return mapping.get(cityId);
}
}
這是我們經常爲類似的事情做的事情。
在何種意義上,你想這個工作? 1234的相關性是什麼? –