Java compareTo() 用法
例如:
public static void main(String[] args) {
BigDecimal bnum1, bnum2;
bnum1 = new BigDecimal("10");
bnum2 = new BigDecimal("20");
int res = bnum1.compareTo(bnum2);
String str1 = "兩個數相等";
String str2 = "第一個數更大";
String str3 = "第二個數更大";
if( res == 0 )
System.out.println( str1 );
else if( res == 1 )
System.out.println( str2 );
else if( res == -1 )
System.out.println( str3 );
}
}
運行代碼,得到以下結果:
第二個數更大
為什么比較返回值是0,-1和1呢? 我們去看看源代碼!
根據源碼中的三元運算符
可以發現:
情況1. 如果xs等於ys,則返回0。
情況2. 如果xs不等於ys,則會執行另外一個三元運算符((xs > ys) ? 1 : -1)
這時候就會比較 xs 和 ys:
xs > ys 返回 1,
xs < ys 返回 -1。
因此得到結論!
兩個數比較的返回值
-
如果第一個參數與第二個參數相等返回0。
-
如果第一個參數小於第二個參數返回 -1。
-
如果第一個參數大於第二個參數返回 1。