Java.lang.Enum.compareTo() 方法
描述
java.lang.Enum.compareTo() 方法将此枚举与指定对象进行比较以获取顺序。枚举常量仅可与相同枚举类型的其他枚举常量进行比较。
声明
以下是 java.lang.Enum.compareTo() 方法的声明。
public final int compareTo(E o)
参数
o − 这是要比较的对象。
返回值
此方法返回负整数、零或正整数,因为此对象小于、等于或大于指定对象。
异常
NA
示例
下面的例子展示了 java.lang.Enum.compareTo() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
// enum showing topics covered under Tutorials
enum Tutorials {
topic1, topic2, topic3;
}
public class EnumDemo {
public static void main(String args[]) {
Tutorials t1, t2, t3;
t1 = Tutorials.topic1;
t2 = Tutorials.topic2;
t3 = Tutorials.topic3;
if(t1.compareTo(t2) > 0) {
System.out.println(t2 + " completed before " + t1);
}
if(t1.compareTo(t2) < 0) {
System.out.println(t1 + " completed before " + t2);
}
if(t1.compareTo(t3) == 0) {
System.out.println(t1 + " completed with " + t3);
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
topic1 completed before topic2

