Java.lang.Enum 类

java.lang.Enum.ordinal() 方法返回此枚举常量的序数(其在枚举声明中的位置) ,其中初始常量被指定零序数)。

语法

public final int ordinal()

参数

无需参数。

返回值

返回此枚举常量的序数。

异常

无。

示例:

在下面的示例中,java.lang.Enum.ordinal() 方法返回给定枚举常量的序数。

import java.lang.*;

public class MyClass {
  
  //创建一个枚举
  public enum WeekDay{
    MON("1st"), TUE("2nd"), WED("3rd"), THU("4th"), FRI("5th");

    String day;
    WeekDay(String x) {
      day = x;
    }

    String showDay() {
      return day;
    }
  }

  public static void main(String[] args) {
    for(WeekDay i : WeekDay.values()) {
      System.out.println("ordinal for " + i + " is " + i.ordinal()); 
      System.out.println(i + " is the " + i.showDay() + " day of the week.");
    }
  }
}

上述代码的输出将是:

ordinal for MON is 0
MON is the 1st day of the week.
ordinal for TUE is 1
TUE is the 2nd day of the week.
ordinal for WED is 2
WED is the 3rd day of the week.
ordinal for THU is 3
THU is the 4th day of the week.
ordinal for FRI is 4
FRI is the 5th day of the week.