Java中所有的枚舉類型都是java.lang.Enum的子類。
本文示例源代碼下載地址:
免費下載地址在 http://linux.linuxidc.com/
用戶名與密碼都是www.linuxidc.com
具體下載目錄在 /2014年資料/6月/4日/Java中的枚舉類型Enum
下載方法見 http://www.linuxidc.com/Linux/2013-07/87684.htm
1. 定義枚舉類型
簡單定義一個枚舉類型,如下:
public enum Week {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY;
}
2. 枚舉類型的常用方法
可以使用枚舉類型的values()靜態方法返回枚舉類型中的所有枚舉值,使用枚舉常量的name()方法返回枚舉常量的名稱,使用枚舉常量的ordinal()方法返回枚舉常量的序數(常量在枚舉聲明中的位置,從0開始)。
示例代碼如下:
public static void main(String[] args) {
//獲取枚舉類型中的全部枚舉值
Week[] days = Week.values();
for(Week day : days) {
//返回枚舉常量的名稱
String name = day.name();
//返回枚舉常量的序數(常量在枚舉聲明中的位置,從0開始)
int ordinal = day.ordinal();
String toString = day.toString();
Class declaringClass = day.getDeclaringClass();
Class superClass = declaringClass.getSuperclass();
System.out.println(
"Name: " + name
+ "\n"
+ "Ordinal: " + ordinal
+ "\n"
+ "ToString: " + toString
+ "\n"
+ "DeclaringClass: " + declaringClass
+ "\n"
+ "SuperClass: " + superClass
+ "\n"
);
}
}
輸出結果如下:
Name: MONDAY
Ordinal: 0
ToString: MONDAY
DeclaringClass: class myEnum.Week
SuperClass: class java.lang.Enum
Name: TUESDAY
Ordinal: 1
ToString: TUESDAY
DeclaringClass: class myEnum.Week
SuperClass: class java.lang.Enum
Name: WEDNESDAY
Ordinal: 2
ToString: WEDNESDAY
DeclaringClass: class myEnum.Week
SuperClass: class java.lang.Enum
Name: THURSDAY
Ordinal: 3
ToString: THURSDAY
DeclaringClass: class myEnum.Week
SuperClass: class java.lang.Enum
Name: FRIDAY
Ordinal: 4
ToString: FRIDAY
DeclaringClass: class myEnum.Week
SuperClass: class java.lang.Enum
Name: SATURDAY
Ordinal: 5
ToString: SATURDAY
DeclaringClass: class myEnum.Week
SuperClass: class java.lang.Enum
Name: SUNDAY
Ordinal: 6
ToString: SUNDAY
DeclaringClass: class myEnum.Week
SuperClass: class java.lang.Enum
更多詳情見請繼續閱讀下一頁的精彩內容: http://www.linuxidc.com/Linux/2014-06/102691p2.htm
Java 8 中 HashMap 的性能提升 http://www.linuxidc.com/Linux/2014-04/100868.htm
Java 8 的 Nashorn 引擎 http://www.linuxidc.com/Linux/2014-03/98880.htm
Java 8簡明教程 http://www.linuxidc.com/Linux/2014-03/98754.htm