当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Integer compareTo()用法及代码示例


java.lang包的Integer类的compareTo()方法以数字方式比较两个Integer对象,如果此Integer等于参数Integer,则返回值0;否则,返回0。如果此Integer在数值上小于参数Integer,则小于0的值;如果此Integer在数值上大于参数Integer(有符号比较),则该值大于0。

用法:

public int compareTo(Integer anotherInt)
参数:
anotherInt-: the Integer to be compared.
返回:
- This method returns the value 0 if this Integer is 
equal to the argument Integer; 
- a value less than 0 if this Integer is 
numerically less than the argument Integer; 
- and a value greater than 0 if this Integer is
numerically greater than the argument Integer
(signed comparison).

例:展示java.lang.Integer.compareTo()方法的用法。


// Java program to demonstrate working 
// of java.lang.Integer.compareTo() method 
import java.lang.Integer; 
  
class Gfg { 
  
    // driver code 
    public static void main(String args[]) 
    { 
        Integer a = new Integer(10); 
        Integer b = new Integer(20); 
  
        // as 10 less than 20, Output will be a value less than zero 
        System.out.println(a.compareTo(b)); 
  
        Integer x = new Integer(30); 
        Integer y = new Integer(30); 
  
        // as 30 equals 30, Output will be zero 
        System.out.println(x.compareTo(y)); 
  
        Integer w = new Integer(15); 
        Integer z = new Integer(8); 
  
        // as 15 is greater than 8, Output will be a value greater than zero 
        System.out.println(w.compareTo(z)); 
    } 
}

输出:

-1
0
1


相关用法


注:本文由纯净天空筛选整理自Niraj_Pandey大神的英文原创作品 Java Integer compareTo() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。