java 枚举做switch,Java使用带有switch语句的枚举

I've looked at various Q&As on SO similar to this question but haven't found a solution.

What I have is an enum which represents different ways to view a TV Guide...

In the NDroid Application class

static enum guideView {

GUIDE_VIEW_SEVEN_DAY,

GUIDE_VIEW_NOW_SHOWING,

GUIDE_VIEW_ALL_TIMESLOTS

}

...when the user changes the view an event handler receives an int from 0-2 and I'd like to do something like this...

In an Android Activity onClick(DialogInterface dialog, int which) event handler

// 'which' is an int from 0-2

switch (which) {

case NDroid.guideView.GUIDE_VIEW_SEVEN_DAY:

...

break;

}

I'm used to C# enums and select/case statements which would allow something like the above and I know Java does things differently but I just can't make sense of what I need to do.

Am I going to have to resort to if statements? There will likely only ever be 3 choices so I could do it but I wondered how it could be done with switch-case in Java.

EDIT Sorry I didn't completely expand on the issue as I was looking at it as being a generic Java issue. I've added to the question to explain a bit further.

There isn't anything that's Android specific which is why I didn't tag it as Android but the enum is defined in the Application class and the code where I wan't the switch is in an Activity. The enum is static as I need to access it from multiple Activities.

解决方案

The part you're missing is converting from the integer to the type-safe enum. Java will not do it automatically. There's a couple of ways you can go about this:

Use a list of static final ints rather than a type-safe enum and switch on the int value you receive (this is the pre-Java 5 approach)

Switch on either a specified id value (as described by heneryville) or the ordinal value of the enum values; i.e. guideView.GUIDE_VIEW_SEVEN_DAY.ordinal()

Determine the enum value represented by the int value and then switch on the enum value.

enum GuideView {

SEVEN_DAY,

NOW_SHOWING,

ALL_TIMESLOTS

}

// Working on the assumption that your int value is

// the ordinal value of the items in your enum

public void onClick(DialogInterface dialog, int which) {

// do your own bounds checking

GuideView whichView = GuideView.values()[which];

switch (whichView) {

case SEVEN_DAY:

...

break;

case NOW_SHOWING:

...

break;

}

}

You may find it more helpful / less error prone to write a custom valueOf implementation that takes your integer values as an argument to resolve the appropriate enum value and lets you centralize your bounds checking.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值