Java using enum with switch statement
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.
If whichView
is an object of the GuideView Enum, following works well. Please note that there is no qualifier for the constant after case
.
switch (whichView) {
case SEVEN_DAY:
...
break;
case NOW_SHOWING:
...
break;
}