使用枚举概念定义 Ordinal() 方法的Java程序
Java枚举,也称为Java枚举类型,是一种字段由一组固定常量组成的类型。
Java.lang.Enum.ordinal()讲述了序数(它是枚举声明中的位置,其中初始常量被分配了零序数) 对于特定的枚举。
ordinal() 方法是一个非静态方法,这意味着它只能通过类对象访问,如果我们尝试访问另一个类的对象,它将给出错误。这是一个最终方法,不能被覆盖。
句法:
public final int ordinal();
返回值:
This method returns the ordinal of this enumeration constant.
Default Value of the Enum is 0 and increment upto the index present in enum.
Like we have declare three index in enum class So the ordinal() value for the enum index is 0, 1, 2
枚举默认序号位置的代码:
Java
// Java program to show the usage of
// ordinal() method of java enumeration
import java.lang.*;
import java.util.*;
// enum showing Student details
enum Student {
Rohit, Geeks,Author;
}
public class GFG {
public static void main(String args[]) {
System.out.println("Student Name:");
for(Student m : Student.values()) {
System.out.print(m+" : "+m.ordinal()+" ");
}
}
}
Java
// Java program to show that the ordinal
// value remainw same whether we mention
// index to the enum or not
import java.lang.*;
import java.util.*;
// enum showing Mobile prices
enum Student_id {
james(3413),
peter(34),
sam(4235);
int id;
Student_id(int Id) { id = Id; }
public int show() { return id; }
}
public class GFG {
public static void main(String args[])
{
// printing all the default ordinary number for the
// enum index
System.out.println("Student Id List: ");
for (Student_id m : Student_id.values()) {
System.out.print(m + " : " + m.ordinal() + " ");
}
System.out.println();
System.out.println("---------------------------");
for (Student_id id : Student_id.values()) {
// printing all the value stored in the enum
// index
System.out.print("student Name : " + id + ": "
+ id.show());
System.out.println();
}
}
}
输出
Student Name:
Rohit : 0 Geeks : 1 Author : 2
我们还可以将值存储到枚举中存在的索引中,但序号值将保持不变。它不会被改变。
代码:
Java
// Java program to show that the ordinal
// value remainw same whether we mention
// index to the enum or not
import java.lang.*;
import java.util.*;
// enum showing Mobile prices
enum Student_id {
james(3413),
peter(34),
sam(4235);
int id;
Student_id(int Id) { id = Id; }
public int show() { return id; }
}
public class GFG {
public static void main(String args[])
{
// printing all the default ordinary number for the
// enum index
System.out.println("Student Id List: ");
for (Student_id m : Student_id.values()) {
System.out.print(m + " : " + m.ordinal() + " ");
}
System.out.println();
System.out.println("---------------------------");
for (Student_id id : Student_id.values()) {
// printing all the value stored in the enum
// index
System.out.print("student Name : " + id + ": "
+ id.show());
System.out.println();
}
}
}
输出
Student Id List:
james : 0 peter : 1 sam : 2
---------------------------
student Name : james: 3413
student Name : peter: 34
student Name : sam: 4235