好吧,我想做这个工作
public static void main(String[] args) {
int cityId = 1234;
switch (cityId) {
case MOSCOW:
System.out.println("Moscow");
break;
case SOCHI:
break;
}
public enum Test {
MOSCOW,
NEWYORK,
SOCHI
}
所以我想将测试枚举与城市 ID 链接起来,这可能吗?这种情况的最佳模式是什么?
谢谢!
最佳答案
你不能在开关中混合使用它。要么你通过 Test
枚举到 switch 语句中,或者在 case 语句中使用常量 ids。
我建议有一个映射 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);
}
}
这是我们经常为类似的事情做的事情。
关于java - 开关语句 : number to enum value/1002 = MyEnum. NewYorkID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7162192/