當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。