Java - compareTo() 方法



描述

該方法將呼叫該方法的 Number 物件與引數進行比較。可以比較 Byte、Long、Integer 等。

但是,不能比較兩種不同的型別,引數和呼叫該方法的 Number 物件都應為同一型別。

語法

public int compareTo( NumberSubClass referenceName )

引數

以下是引數的詳細資訊 -

  • referenceName - 這可以是 Byte、Double、Integer、Float、Long 或 Short。

返回值

  • 如果 Integer 大於引數,則返回 1。
  • 如果 Integer 等於引數,則返回 0。
  • 如果 Integer 小於引數,則返回 -1。

比較 Integer 值示例

在此示例中,我們展示了 compareTo() 方法用於比較 Integer 的用法。我們建立了一個 Integer 變數 x 並將其初始化為值 5。然後使用 compareTo() 方法,我們將其與多個值(如 3、5 和 8)進行比較以涵蓋多種情況。

public class Test {
   public static void main(String args[]) {
      Integer x = 5;
      
      // Integer value is greater than the argument (5 > 3) so, output is 1
      System.out.println(x.compareTo(3));
      
      // Integer value is equal to the argument so, output is 0
      System.out.println(x.compareTo(5));
      
      // Integer value is less than the argument (5 < 8) so, output is −1
      System.out.println(x.compareTo(8));            
   }
}

輸出

這將產生以下結果 -

1
0
-1

比較 Float 值示例

在此示例中,我們展示了 compareTo() 方法用於比較浮點值的用法。我們建立了一個 Float 變數 x 並將其初始化為值 5.0。然後使用 compareTo() 方法,我們將其與多個值(如 3.0、5.0 和 8.0)進行比較以涵蓋多種情況。

public class Test {
   public static void main(String args[]) {
      Float x = (float) 5.0;
      
      // Float value is greater than the argument (5.0 > 3.0) so, output is 1
      System.out.println(x.compareTo((float) 3.0));
      
      // Float value is equal to the argument so, output is 0
      System.out.println(x.compareTo((float) 5.0));
      
      // Float value is less than the argument (5.0  < 8.0) so, output is −1
      System.out.println(x.compareTo((float) 8.0));            
   }
}

輸出

這將產生以下結果 -

1
0
-1

比較 Double 值示例

在此示例中,我們展示了 compareTo() 方法用於比較雙精度值的用法。我們建立了一個 Double 變數 x 並將其初始化為值 5.0。然後使用 compareTo() 方法,我們將其與多個值(如 3.0、5.0 和 8.0)進行比較以涵蓋多種情況。

public class Test {
   public static void main(String args[]) {
      Double x = 5.0;
      
      // Double value is greater than the argument (5.0>3.0) so, output is 1
      System.out.println(x.compareTo(3.0));
      
      // Double value is equal to the argument so, output is 0
      System.out.println(x.compareTo(5.0));
      
      // Double value is less than the argument (5.0<8.0) so, output is −1
      System.out.println(x.compareTo(8.0));            
   }
}

輸出

這將產生以下結果 -

1
0
-1
java_numbers.htm
廣告