Switch on Enum in Java [duplicate]
You definitely can switch on enums. An example posted from the Java tutorials.
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
}
You actually can switch
on enum
s, but you can't switch
on String
s until Java 7. You might consider using polymorphic method dispatch with Java enum
s rather than an explicit switch
. Note that enum
s are objects in Java, not just symbols for int
s like they are in C/C++. You can have a method on an enum
type, then instead of writing a switch
, just call the method - one line of code: done!
enum MyEnum {
SOME_ENUM_CONSTANT {
@Override
public void method() {
System.out.println("first enum constant behavior!");
}
},
ANOTHER_ENUM_CONSTANT {
@Override
public void method() {
System.out.println("second enum constant behavior!");
}
}; // note the semi-colon after the final constant, not just a comma!
public abstract void method(); // could also be in an interface that MyEnum implements
}
void aMethodSomewhere(final MyEnum e) {
doSomeStuff();
e.method(); // here is where the switch would be, now it's one line of code!
doSomeOtherStuff();
}