Java - 列舉compareTo() 方法



描述

Java Enum compareTo() 方法比較此列舉與指定物件的順序。列舉常量只能與相同列舉型別的其他列舉常量進行比較。

宣告

以下是java.lang.Enum.compareTo() 方法的宣告

public final int compareTo(E o)

引數

o − 這是要比較的物件。

返回值

此方法返回一個負整數、零或正整數,具體取決於此物件小於、等於或大於指定物件。

異常

比較列舉值示例

以下示例演示瞭如何使用 compareTo() 方法比較相同列舉型別的各種列舉值,以檢查大於 0 的結果。

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 的結果。

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 的結果。

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
廣告
© . All rights reserved.