目录

compareTo()

compareTo方法是使用一个数字与另一个数字进行比较。 如果要比较数字的值,这很有用。

语法 (Syntax)

public int compareTo( NumberSubClass referenceName ) 

参数 (Parameters)

referenceName - 可以是Byte,Double,Integer,Float,Long或Short。

返回值 (Return Value)

  • 如果Integer等于参数,则返回0。
  • 如果Integer小于参数,则返回-1。
  • 如果Integer大于参数,则返回1。

例子 (Example)

以下是此方法的使用示例 -

class Example { 
   static void main(String[] args) { 
      Integer x = 5;
      //Comparison against a Integer of lower value 
      System.out.println(x.compareTo(3));
      //Comparison against a Integer of equal value 
      System.out.println(x.compareTo(5)); 
      //Comparison against a Integer of higher value 
      System.out.println(x.compareTo(8)); 
   } 
} 

当我们运行上述程序时,我们将得到以下结果 -

1 
0 
-1 
↑回到顶部↑
WIKI教程 @2018