Java.math.BigInteger.compareTo() 方法
描述
java.math.BigInteger.compareTo(BigInteger val) 将此 BigInteger 与指定的 BigInteger 进行比较。 此方法优先于六个布尔比较运算符 (<, ==, >, >=, !=, <=) 中的每一个的单独方法提供。
执行这些比较的建议习惯用法是:(x.compareTo(y) <op> 0),其中 <op> 是六个比较运算符之一。
声明
以下是 java.math.BigInteger.compareTo() 方法的声明。
public int compareTo(BigInteger val)
指定者
compareTo 在接口 Comparable<BigInteger> 中。
参数
val − BigInteger 要与此 BigInteger 进行比较。
返回值
此方法返回 -1、0 或 1,因为此 BigInteger 在数值上小于、等于或大于 val。
异常
NA
示例
下面的例子展示了 math.BigInteger.compareTo() 方法的使用。
package com.tutorialspoint;
import java.math.*;
public class BigIntegerDemo {
public static void main(String[] args) {
// create 2 BigInteger objects
BigInteger bi1, bi2;
bi1 = new BigInteger("6");
bi2 = new BigInteger("3");
// create int object
int res;
// compare bi1 with bi2
res = bi1.compareTo(bi2);
String str1 = "Both values are equal ";
String str2 = "First Value is greater ";
String str3 = "Second value is greater";
if( res == 0 )
System.out.println( str1 );
else if( res == 1 )
System.out.println( str2 );
else if( res == -1 )
System.out.println( str3 );
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
First Value is greater

