Switch 语句:数字到枚举值 / 1002 = MyEnum.NewYorkID
好吧,我想让这个工作成功
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
}
所以我想将 Test 枚举与城市 id 链接起来,这可能吗?对于这种情况,最好的模式是什么?
谢谢你!
Well, I want to make this work
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
}
So I want to link Test enum with city ids, is that possible? What is the best pattern for this situation?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能将其混合在一个开关中。您可以将
Test
枚举传递到 switch 语句中,或者在 case 语句中使用常量 id。我建议有一个映射
cityId <->在调用开关之前测试实例并进行转换。
像编辑这样的东西
:请注意,您可以将此映射放入枚举中,将 cityId 字段添加到枚举中,并自动填充
values()
返回的数组中的映射,就像 Chris 的建议一样。这是我们经常为类似的事情做的事情。
You can't mix that in a switch. Either you pass a
Test
enum into the switch statement, or use the constant ids in the case statements.I'd suggest having a mapping
cityId <-> Test instance
and converting before calling the switch.Something like
Edit: note that you could put this mapping into the enum, add a cityId field to the enum and automatically fill the mapping from the array returned by
values()
, much like Chris' suggestion.That's something we often do for similar things.
您的代码的唯一问题是您需要打开
Test
而不是int
。IE:
The only problem with your code is that you need to switch on
Test
notint
.ie:
您可以在枚举中添加一个
cityId
字段:然后您确实可以打开枚举值:
You can add a
cityId
field in your enum:Then you can indeed switch on the enum value: