compareTo方法是使用比較一個數(shù)字與另一個數(shù)字。如果要比較數(shù)字的值,這是有用的。
public int compareTo( NumberSubClass referenceName )
referenceName - 這可以是字節(jié),雙精度,整數(shù),浮點(diǎn)型,長整型或短整型。
下面是一個使用這個方法的例子 -
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)); } }
當(dāng)我們運(yùn)行上面的程序,我們將得到以下結(jié)果 -
1 0 -1
更多建議: