[java] Java using enum with switch statement

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.

This question is related to java enums switch-statement

The answer is


I am doing it like

public enum State
{
    // Retrieving, // the MediaRetriever is retrieving music //
    Stopped, // media player is stopped and not prepared to play
    Preparing, // media player is preparing...
    Playing, // playback active (media player ready!). (but the media player
                // may actually be
                // paused in this state if we don't have audio focus. But we
                // stay in this state
                // so that we know we have to resume playback once we get
                // focus back)
    Paused; // playback paused (media player ready!)

    //public final static State[] vals = State.values();//copy the values(), calling values() clones the array

};

public State getState()
{
        return mState;   
}

And use in Switch Statement

switch (mService.getState())
{
case Stopped:
case Paused:

    playPause.setBackgroundResource(R.drawable.selplay);
    break;

case Preparing:
case Playing:

    playPause.setBackgroundResource(R.drawable.selpause);
    break;    
}

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;
}

This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.


I like a few usages of Java enum:

  1. .name() allows you to fetch the enum name in String.
  2. .ordinal() allow you to get the integer value, 0-based.
  3. You can attach other value parameters with each enum.
  4. and, of course, switch enabled.

enum with value parameters:

    enum StateEnum {
        UNDEFINED_POLL  ( 1 * 1000L,       4 * 1000L),
        SUPPORT_POLL    ( 1 * 1000L,       5 * 1000L),
        FAST_POLL       ( 2 * 1000L,  4 * 60 * 1000L),
        NO_POLL         ( 1 * 1000L,       6 * 1000L); 
        ...
    }

switch example:

private void queuePoll(StateEnum se) {
    // debug print se.name() if needed
    switch (se) {
        case UNDEFINED_POLL:
            ...
            break;
        case SUPPORT_POLL:
            ...
            break;

The enums should not be qualified within the case label like what you have NDroid.guideView.GUIDE_VIEW_SEVEN_DAY, instead you should remove the qualification and use GUIDE_VIEW_SEVEN_DAY


Short associative function example:

public String getIcon(TipoNotificacao tipo)
{
    switch (tipo){
        case Comentou : return "fa fa-comments";
        case ConviteEnviou : return "icon-envelope";
        case ConviteAceitou : return "fa fa-bolt";
        default: return "";
    }
}

Like @Dhanushka said, omit the qualifier inside "switch" is the key.


enumerations accessing is very simple in switch case

private TYPE currentView;

//declaration of enum 
public enum TYPE {
        FIRST, SECOND, THIRD
    };

//handling in switch case
switch (getCurrentView())
        {
        case FIRST:
            break;
        case SECOND:
            break;
        case THIRD:
            break;
        }

//getter and setter of the enum
public void setCurrentView(TYPE currentView) {
        this.currentView = currentView;
    }

    public TYPE getCurrentView() {
        return currentView;
    }

//usage of setting the enum 
setCurrentView(TYPE.FIRST);

avoid the accessing of TYPE.FIRST.ordinal() it is not recommended always

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to enums

Enums in Javascript with ES6 Check if value exists in enum in TypeScript Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'? TypeScript enum to object array How can I loop through enum values for display in radio buttons? How to get all values from python enum class? Get enum values as List of String in Java 8 enum to string in modern C++11 / C++14 / C++17 and future C++20 Implementing Singleton with an Enum (in Java) Swift: Convert enum value to String?

Examples related to switch-statement

Switch in Laravel 5 - Blade Switch case: can I use a range instead of a one number SQL use CASE statement in WHERE IN clause SSRS Conditional Formatting Switch or IIF Switch statement equivalent in Windows batch file OR operator in switch-case? Regarding Java switch statements - using return and omitting breaks in each case Using two values for one switch case statement C# how to use enum with switch Switch statement multiple cases in JavaScript