Enum 类的 ordinal() 方法返回这个枚举常量的序号。
此方法旨在供复杂的基于枚举的数据结构使用,如 EnumSet 和 EnumMap。
用法
public final int ordinal()
返回值
ordinal() 方法返回这个枚举常量的序号。
例子1
public class Enum_ordinalMethodExample1 {
enum Colours{
Red,Green,Brown,Yellow;
}
public static void main(String[] args) {
Colours Red = Colours.Red;
Colours Green = Colours.Green;
Colours Brown = Colours.Brown;
Colours Yellow = Colours.Yellow;
System.out.println(" Red ordinal = "+Red.ordinal());
System.out.println(" Green Ordinal = "+Green.ordinal());
System.out.println(" Brown Ordinal = "+Brown.ordinal());
System.out.println(" Yellow Ordinal = "+Yellow.ordinal());
}
}
输出:
Red ordinal = 0 Green Ordinal = 1 Brown Ordinal = 2 Yellow Ordinal = 3
例子2
public class Enum_ordinalMethodExample2 {
enum Position{
Reema("Panda"),Himanshu("Bhardwaj"),Geetanjali("Sharma");
String lName;
Position(String s){
lName=s;
}
String showPosition(){
return lName;
}
}
public static void main(String[] args) {
for(Position pos:Position.values()){
int val = pos.ordinal()+1;
System.out.println("First name = "+pos+"\nLast name = "+pos.showPosition() +"\nPosition in class = "+val );
System.out.println();
}
}
}
输出:
First name = Reema Last name = Panda Position in class = 1 First name = Himanshu Last name = Bhardwaj Position in class = 2 First name = Geetanjali Last name = Sharma Position in class = 3
例子3
public class Enum_ordinalMethodExample3 {
enum movie{
Don,DDlJ,Fan,Zero,VeerZara;
}
public static void main(String[] args) {
movie Don,DDLJ,Fan,Zero;
Zero= movie.Zero;
System.out.println("Movies of Shahrukh Khan:");
for(movie m:movie.values()){
// method will return the ordinals of the enum constants
System.out.println(m.ordinal()+" "+m);
}
System.out.println("Q In which movie Shah rukh khan has played a dual role ?");
String obj1="Don";
String obj2 ="Zero";
Boolean b1 =obj1.equals(obj2);
System.out.println("Ans. "+Zero.ordinal()+" "+ obj2 );
if(b1==true){
System.out.println("Your answer is correct.");
}
else{
System.out.println("Sorry!You Failed.\n The Correct answer is Don.");
}
}
}
输出:
Movies of Shahrukh Khan: 0 Don 1 DDlJ 2 Fan 3 Zero 4 VeerZara Q In which movie Shah rukh khan has played a dual role ? Ans. 3 Zero Sorry!You Failed. The Correct answer is Don.
相关用法
- Java Enum ordinal()用法及代码示例
- Java Enum equals()用法及代码示例
- Java Enum toString()用法及代码示例
- Java Enum valueOf()用法及代码示例
- Java Enum hashCode()用法及代码示例
- Java Enum finalize()用法及代码示例
- Java Enum clone()用法及代码示例
- Java Enum name()用法及代码示例
- Java Enum getDeclaringClass()用法及代码示例
- Java Enum compareTo()用法及代码示例
- Java EnumSet range()用法及代码示例
- Java EnumMap remove()用法及代码示例
- Java EnumMap hashCode()用法及代码示例
- Java EnumMap get()用法及代码示例
- Java EnumSet complementOf()用法及代码示例
- Java EnumSet clone()用法及代码示例
- Java EnumMap entrySet()用法及代码示例
- Java EnumMap containsKey()用法及代码示例
- Java EnumMap containsValue(value)用法及代码示例
- Java Enumeration asIterator()用法及代码示例
注:本文由纯净天空筛选整理自 Java Enum ordinal() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。