大家好,又见面了,我是你们的朋友全栈君。
例如:
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。
因此得到结论!
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/159883.html原文链接:https://javaforall.cn