Java中的枚举类型Enum

免费下载地址在

用户名与密码都是

具体下载目录在 /2014年资料/6月/4日/Java中的枚举类型Enum

下载方法见

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.heiqu.com/ff3476458ca4a130550c7fdef3af29f5.html