Java 枚舉類型(Enum)是一種特殊的類,用于表示固定數(shù)量的常量值。枚舉類型的主要用途如下:
public enum Weekday {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Weekday day = Weekday.MONDAY;
switch (day) {
case SUNDAY:
System.out.println("Sunday");
break;
case MONDAY:
System.out.println("Monday");
break;
// ...
}
public enum Size {
SMALL, MEDIUM, LARGE
}
public Size getBestSize(int width, int height) {
// ...
}
public enum Singleton {
INSTANCE;
private String message;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
public enum State {
START, RUNNING, PAUSED, STOPPED
}
public class StateMachine {
private State state;
public void setState(State state) {
this.state = state;
}
// ...
}
總之,Java 枚舉類型提供了一種簡潔、可讀性強(qiáng)的方式來表示和處理一組固定的常量值。