Java - 列舉 ordinal() 方法



描述

Java Enum ordinal() 方法返回此列舉常量的序數(在其列舉宣告中的位置,其中初始常量被分配序數 0)。

宣告

以下是 java.lang.Enum.ordinal() 方法的宣告

public final int ordinal()

引數

返回值

此方法返回此列舉常量的序數。

異常

獲取列舉的序數示例

以下示例演示了使用其引用的列舉的 ordinal() 方法的用法。

package com.tutorialspoint;

// enum showing topics covered under Tutorials
enum Tutorials {  
   Java, HTML, Python; 
}  
public class EnumDemo { 
   public static void main(String args[]) { 
      Tutorials t1, t2, t3;     
      t1 = Tutorials.Java; 
      t2 = Tutorials.HTML; 
      t3 = Tutorials.Python; 
    
      // returns the ordinal corresponding to an enum
      System.out.println(t1.ordinal()); 
      System.out.println(t2.ordinal()); 
      System.out.println(t3.ordinal()); 
   } 
} 

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

0
1
2

獲取列舉的序數示例

以下示例演示了使用其型別的列舉的 ordinal() 方法的用法。

package com.tutorialspoint;

// enum showing topics covered under Tutorials
enum Tutorials {  
   Java, HTML, Python; 
}  
public class EnumDemo { 
   public static void main(String args[]) {
    
      // returns the ordinal corresponding to an enum
      System.out.println(Tutorials.Java.ordinal()); 
      System.out.println(Tutorials.HTML.ordinal()); 
      System.out.println(Tutorials.Python.ordinal()); 
   } 
} 

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

0
1
2
java_lang_enum.htm
廣告

© . All rights reserved.