Switch on Enum in Java
Switch on Enum in Java
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 cant 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 its one line of code!
doSomeOtherStuff();
}
Switch on Enum in Java
First, you can switch on an enum
in Java. Im guessing you intended to say you can’t, but you can. char
s have a set range of values, so its easy to compare. Strings can be anything.
A switch
statement is usually implemented as a jump table (branch table) in the underlying compilation, which is only possible with a finite set of values. C# can switch on strings, but it causes a performance decrease because a jump table cannot be used.
Java 7 and later supports String
switches with the same characteristics.