Java - 枚举compareTo() 方法



描述

Java Enum compareTo() 方法比较此枚举与指定对象的顺序。枚举常量只能与相同枚举类型的其他枚举常量进行比较。

声明

以下是java.lang.Enum.compareTo() 方法的声明

public final int compareTo(E o)

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

参数

o − 这是要比较的对象。

返回值

此方法返回一个负整数、零或正整数,具体取决于此对象小于、等于或大于指定对象。

异常

比较枚举值示例

以下示例演示了如何使用 compareTo() 方法比较相同枚举类型的各种枚举值,以检查大于 0 的结果。

Open Compiler
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; t1 = Tutorials.Java; t2 = Tutorials.HTML; if(t1.compareTo(t2) > 0) { System.out.println(t2 + " completed before " + t1); } else if(t1.compareTo(t2) < 0) { System.out.println(t1 + " completed before " + t2); } else if(t1.compareTo(t2) == 0) { System.out.println(t1 + " completed with " + t2); } } }

输出

让我们编译并运行上述程序,这将产生以下结果:

Java completed before HTML

比较枚举值示例

以下示例演示了如何使用 compareTo() 方法比较相同枚举类型的各种枚举值,以检查等于 0 的结果。

Open Compiler
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; t1 = Tutorials.HTML; t2 = Tutorials.HTML; if(t1.compareTo(t2) > 0) { System.out.println(t2 + " completed before " + t1); } else if(t1.compareTo(t2) < 0) { System.out.println(t1 + " completed before " + t2); } else if(t1.compareTo(t2) == 0) { System.out.println(t1 + " completed with " + t2); } } }

输出

让我们编译并运行上述程序,这将产生以下结果:

HTML completed with HTML

比较枚举值示例

以下示例演示了如何使用 compareTo() 方法比较相同枚举类型的各种枚举值,以检查小于 0 的结果。

Open Compiler
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; t1 = Tutorials.HTML; t2 = Tutorials.Python; if(t1.compareTo(t2) > 0) { System.out.println(t2 + " completed before " + t1); } else if(t1.compareTo(t2) < 0) { System.out.println(t1 + " completed before " + t2); } else if(t1.compareTo(t2) == 0) { System.out.println(t1 + " completed with " + t2); } } }

输出

让我们编译并运行上述程序,这将产生以下结果:

HTML completed before Python
java_lang_enum.htm
广告