第30條 用enum代替int常量
1. enum與int枚舉對比
古老的int枚舉:
public static final int APPLE_FUJI = 0;
public static final int APPLE_PIPPIN = 0;
public static final int APPLE_GRANNY_SMITH = 0;
public static final int ORANGE_FUJI = 0;
public static final int ORANGE_PIPPIN = 0;
public static final int ORANGE_GRANNY_SMITH = 0;
enum枚舉:
public enum Apple{FUJI,PIPPIN,GRANNY_SMITH};
public enum Orange{FUJI,PIPPIN,GRANNY_SMITH};
enum枚舉較之於int枚舉的優勢:
- 語義化,簡潔
- 類型安全(當需要傳入Apple類型時,enum可以在編譯時期檢查是否傳的正確,而int枚舉不可以)
- enum可以有自己的方法與構造器(構造器私有),更加靈活,功能更強大
2. enum枚舉的特點
- 每個枚舉常量相當於有static final修飾;
- 枚舉類的構造器爲private,外界無法創建其實例(但可以調用其內部唯一常量,作爲單例模式);
- 編譯時期類型安全
3. enum枚舉實例
public enum EnumTest {
RED("red", 1), GREEN("green", 2), BLUE("blue", 3);
private String name;
private int num;
EnumTest(String name, int num) {
this.name = name;
this.num = num;
}
public String getName() {
return name;
}
public int getNum() {
return num;
}
}
4. 特定於常量的方法實現(即對方法枚舉)
public enum Operation{
PLUS{double apply(double x,double y) {return x+y;}},
MINUS{double apply(double x,double y) {return x-y;}};
abstract double apply(double x,double y);
}
實質是對方法的枚舉,使用時爲Operation.PLUS.apply(x,y)。注意enum的前綴仍爲static final。
每個枚舉常量都要繼承apply抽象方法。
第31條 用實例域代替序數
每個枚舉常量在枚舉表中的位置可用ordinal()函數獲取。但不建議使用該方法,因爲一旦枚舉常量在枚舉表中的位置改變,ordinal()獲取的位置也會發生改變(除非你是真的只想獲取它的位置)。
建議使用如
public enum Test{
A(1),B(2);
private int location;
Test(int location){
this.location=location;
}
public int getLocation(){
return location;
}
}
便於以後的修改與擴展。