比較 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

更新於: 18-6-2020

1.5 萬+ 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告