3 回答

TA贡献1877条经验 获得超6个赞
实际上,您可以switch使用enums,但是直到Java 7才可以switch使用Strings。您可以考虑将Java enum的多态方法分派使用,而不是显式switch。请注意,enums是Java中的对象,而不仅仅是ints的符号,就像在C / C ++中一样。您可以在enum类型上有一个方法,然后不用编写a switch,只需调用该方法-一行代码即可:完成!
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();
}
添加回答
举报