比较Java枚举成员\n
java.lang.Enum类是所有Java语言枚举类型共同的基类。
类声明
以下是java.lang.Enum类的声明 -
public abstract class Enum<E extends Enum<E>> extends Object implements Comparable<E>, Serializable
我们可以使用以下方式比较枚举变量。
使用 Enum.compareTo() 方法。compareTo() 方法按顺序比较该枚举与指定的对象。
使用 Enum.equals() 方法。如果指定的对象等于此枚举常量,equals() 方法返回 true。
使用 == 运算符。== 运算符检查类型并对相同类型的枚举常量进行空安全比较。
示例
public class Tester { // enum showing topics covered under Tutorials enum Tutorials { TOPIC_1, TOPIC_2, TOPIC_3; } public static void main(String[] args) { Tutorials t1, t2, t3; t1 = Tutorials.TOPIC_1; t2 = Tutorials.TOPIC_2; t3 = Tutorials.TOPIC_3; //Comparing using compareTo() method 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(t2) == 0) { System.out.println(t1 + " completed with " + t2); } //Comparing using == //In this case t1 can be null as well causing no issue if(t1 == Tutorials.TOPIC_1) { System.out.println("t1 = TOPIC_1"); }else { System.out.println("t1 != TOPIC_1"); } //Comparing using equals() method //In this case t2 cannot be null. It will cause //null pointer exception if(t2.equals(Tutorials.TOPIC_2)) { System.out.println("t2 = TOPIC_2"); }else { System.out.println("t2 != TOPIC_2"); } Tutorials t4 = null; //Comparing using equals() method //in null safe manner if(Tutorials.TOPIC_3.equals(t4)) { System.out.println("t4 = TOPIC_3"); }else { System.out.println("t4 != TOPIC_3"); } } }
输出
TOPIC_1 completed before TOPIC_2 t1 = TOPIC_1 t2 = TOPIC_2 t4 != TOPIC_3
广告