compareTo方法是使用比较一个数字与另一个数字。如果要比较数字的值,这是有用的。
句法
- public int compareTo( NumberSubClass referenceName )
参数
referenceName - 这可以是字节,双精度,整数,浮点型,长整型或短整型。
返回值
- 如果整数等于参数,则返回0。
- 如果整数小于参数,则返回-1。
- 如果整数大于参数,则返回1。
例子
下面是一个使用这个方法的例子 -
- 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
转载本站内容时,请务必注明来自W3xue,违者必究。