3 回答

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
實(shí)際上,您可以switch使用enums,但是直到Java 7才可以switch使用Strings。您可以考慮將Java enum的多態(tài)方法分派使用,而不是顯式switch。請注意,enums是Java中的對象,而不僅僅是ints的符號(hào),就像在C / C ++中一樣。您可以在enum類型上有一個(gè)方法,然后不用編寫a switch,只需調(diào)用該方法-一行代碼即可:完成!
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();
}
添加回答
舉報(bào)