對於:
enum Color { RED,BLUE,BLACK YELLOW,GREEN};
(1) ordinal()方法: 返回枚舉值在枚舉類種的順序。這個順序根據枚舉值聲明的順序而定。
Color.RED.ordinal(); //返回結果:0
Color.BLUE.ordinal(); //返回結果:1
(2) compareTo()方法: Enum實現了java.lang.Comparable介面,因此可以比較象與指定對象的順序。Enum中的compareTo返回的是兩個枚舉值的順序之差。當然,前提是兩個枚舉值必須屬於同一個枚舉類,否則會拋出ClassCastException()異常。(具體可見原始碼)
Color.RED.compareTo(Color.BLUE); //返回結果 -1
(3) values()方法: 靜態方法,返回一個包含全部枚舉值的數組。
Color[] colors=Color.values();
for(Color c:colors){
System.out.print(c+",");
}//返回結果:RED,BLUE,BLACK YELLOW,GREEN,
(4) toString()方法: 返回枚舉常量的名稱。
Color c=Color.RED;
System.out.println(c);//返回結果: RED
(5) valueOf()方法: 這個方法和toString方法是相對應的,返回帶指定名稱的指定枚舉類型的枚舉常量。
Color.valueOf("BLUE"); //返回結果: Color.BLUE
(6) equals()方法: 比較兩個枚舉類對象的引用。
總結:
1. enum<->int
enum -> int: int i = enumType.value.ordinal();
int -> enum: enumType b= enumType.values()[i];
2. enum<->String
enum -> String: enumType.name()
String -> enum: enumType.valueOf(name);