Friday, July 9, 2010

How to use Enums in Switch (java)

In a small example I am going to tell you how to use enums in switch.
Enums is a good practice of grouping a list of items which fall in similar category. If you want to learn more about enums look in to here.

Now I assume that you know about enums and now lets see how do we swtich on them.
This is my enum set
public static enum Navigation{SCROLL,DROP_DOWN,NONE}

Now you need to switch on the enum.
we write
//choice is
Navigation navigationChoice = Navigation.SCROLL;
switch (navigationChoice) //once decide to switch on the Enumof type navigation choice.
{
Since we already are switching on the Naviagation enum Java knows to look only with the Navigation enum the context is set to Navigation enum so we need not have fully qualified name Navigation.SCROLL . We can just use SCROLL instead.

CORRECT WAY TO DO:
case SCROLL: {...}
CORRECT: We use the unqualified name i.e. SCROLL and Java will automatically know that we are asking for scroll in the navigation options as we are switching on a Navigation enum constant.

WRONG WAY TO DO:
case Navigation.DROP_DOWN: {...}
This will give you error the follwing error
ERROR: The qualified case label Navigation.DROP_DOWN must be replaced with the unqualified enum constant DROP_DOWN

WRONG WAY TO DO:
case (NONE): {...}
This will give you error the follwing error
ERROR: Enum constants cannot be surrounded by parenthesis
}


No comments:

Post a Comment